Start on using context api, preserving state and will allow for moving some thing inline to components without prop drilling.
parent
cf3176f811
commit
6257420ef0
5 changed files with 89 additions and 50 deletions
@ -0,0 +1,15 @@ |
||||
import { createContext, useReducer } from 'react'; |
||||
import reducer from './GlobalReducer.js'; |
||||
|
||||
export const GlobalContext = createContext(); |
||||
|
||||
const initialState = {}; |
||||
|
||||
export default function GlobalProvider(props) { |
||||
const [state, dispatch] = useReducer(reducer, initialState); |
||||
return ( |
||||
<GlobalContext.Provider value={[state, dispatch]}> |
||||
{props.children} |
||||
</GlobalContext.Provider> |
||||
); |
||||
} |
@ -0,0 +1,14 @@ |
||||
// reducer.js
|
||||
export default function reducer(state, action) { |
||||
//could do somethig na bit more smart than this
|
||||
switch (action.type) { |
||||
case 'error': |
||||
// Add error, keep existing state
|
||||
return { error: action.payload, ...state }; |
||||
case 'state': |
||||
// Keep state, overwrite or add new values from payload, and null error
|
||||
return { ...state, ...action.payload, error: null }; |
||||
default: |
||||
throw new Error(); |
||||
} |
||||
} |
Loading…
Reference in new issue