SHARE
TWEET

Untitled

a guest Oct 13th, 2019 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // ... MapState.tsx
  2. import React, { createContext, useReducer, useContext } from 'react';
  3.  
  4. type MapState = {
  5.   /** The map feature reference */
  6.   featureRef: any | null;
  7. };
  8.  
  9. type MapActions =
  10.   | {
  11.       type: 'setFeatureRef';
  12.       nextFeatureRef: any;
  13.     }
  14.   | {
  15.       type: 'resetFeatureRef';
  16.     }
  17.  
  18. // By setting the typings here, we ensure we get intellisense in VS Code
  19. const initialMapContext: { mapState: MapState; setMapState: React.Dispatch<MapActions> } = {
  20.   mapState: initialState,
  21.   // will update to the reducer we provide in MapProvider
  22.   setMapState: () => {}
  23. };
  24.  
  25. // No need to export this as we use it internally only
  26. const MapContext = createContext(initialMapContext);
  27.  
  28. const reducer = (state: MapState, action: MapActions) => {
  29.   switch (action.type) {
  30.     case 'setFeatureRef':
  31.       return {
  32.         featureRef: action.nextFeatureRef,
  33.       };
  34.     case 'resetMapFeature':
  35.       return {
  36.         featureRef: null,
  37.       };    
  38.     default:
  39.       return state;
  40.   }
  41. };
  42.  
  43. export function MapProvider({ children }: MapProviderProps) {
  44.   const [state, dispatch] = useReducer(reducer, initialState);
  45.  
  46.   // rename the useReducer result to something more useful
  47.   const mapState = state;
  48.   const setMapState = dispatch;
  49.  
  50.   return <MapContext.Provider value={{ mapState, setMapState }}>{children}</MapContext.Provider>;
  51. }
  52.  
  53. /**
  54.  * To use and set the state of the map from anywhere in the app
  55.  * - @returns an object with a reducer function `setMapState` and the `mapState`
  56.  */
  57. export const useMapState = () => useContext(MapContext);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top