Advertisement
Guest User

Untitled

a guest
Oct 13th, 2019
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  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);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement