gloriaJun / til

Lessoned Learned
3 stars 0 forks source link

React context API #78

Open gloriaJun opened 4 years ago

gloriaJun commented 4 years ago

I'm not sure it is the best practice or not. But it is the best of the present

// A generic typescript interface to capture state based actions. export interface IStateAction { type: string; payload: any; }

export type IDispatch = React.Dispatch;

// Interface to define the basic props for the provider component export interface IStateProviderProps { children: React.ReactNode; }


- provider

```javascript
import React, { useReducer, useContext } from 'react';

import { IStateAction, IDispatch, IStateProviderProps } from 'interfaces';

interface IAppState {
  isInternalFlow: boolean;
}

// The default state
const initialState: IAppState = {
  isInternalFlow: false,
};

export enum appActionTypes {
  SET_INTERNAL_FLOW = 'SET_INTERNAL_FLOW',
}

function appReducer(state: IAppState, action: IStateAction): IAppState {
  const { type, payload } = action;

  switch (type) {
    case appActionTypes.SET_INTERNAL_FLOW: {
      return {
        ...state,
        isInternalFlow: payload,
      };
    }

    default:
      throw new Error('Unhandled action');
  }
}

const AppStateContext = React.createContext<IAppState>({} as IAppState);
const AppDispatchContext = React.createContext<IDispatch>(null as any);

export function AppProvider({ children }: IStateProviderProps): JSX.Element {
  const [state, dispatch] = useReducer(appReducer, initialState);

  return (
    <AppStateContext.Provider value={state}>
      <AppDispatchContext.Provider value={dispatch}>
        {children}
      </AppDispatchContext.Provider>
    </AppStateContext.Provider>
  );
}

export function useAppState(): IAppState {
  return useContext(AppStateContext);
}

export function useAppDispatch(): IDispatch {
  return useContext(AppDispatchContext);
}

Reference