Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ... MapState.tsx
- import React, { createContext, useReducer, useContext } from 'react';
- type MapState = {
- /** The map feature reference */
- featureRef: any | null;
- };
- type MapActions =
- | {
- type: 'setFeatureRef';
- nextFeatureRef: any;
- }
- | {
- type: 'resetFeatureRef';
- }
- // By setting the typings here, we ensure we get intellisense in VS Code
- const initialMapContext: { mapState: MapState; setMapState: React.Dispatch<MapActions> } = {
- mapState: initialState,
- // will update to the reducer we provide in MapProvider
- setMapState: () => {}
- };
- // No need to export this as we use it internally only
- const MapContext = createContext(initialMapContext);
- const reducer = (state: MapState, action: MapActions) => {
- switch (action.type) {
- case 'setFeatureRef':
- return {
- featureRef: action.nextFeatureRef,
- };
- case 'resetMapFeature':
- return {
- featureRef: null,
- };
- default:
- return state;
- }
- };
- export function MapProvider({ children }: MapProviderProps) {
- const [state, dispatch] = useReducer(reducer, initialState);
- // rename the useReducer result to something more useful
- const mapState = state;
- const setMapState = dispatch;
- return <MapContext.Provider value={{ mapState, setMapState }}>{children}</MapContext.Provider>;
- }
- /**
- * To use and set the state of the map from anywhere in the app
- * - @returns an object with a reducer function `setMapState` and the `mapState`
- */
- export const useMapState = () => useContext(MapContext);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement