Created
August 7, 2020 03:09
-
-
Save psaia/679c9e05ed6d7bd7ba5687ca283b0f41 to your computer and use it in GitHub Desktop.
Redux style store without Redux.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useReducer } from "react"; | |
import { CheckType } from "./types"; | |
import update from "immutability-helper"; | |
interface Action { | |
type: string; | |
payload: any; // @TODO | |
} | |
interface State { | |
selectedHealthCheck: CheckType; | |
selectedHealthStatus: boolean; | |
selectedHealthDetails: any; // @TODO | |
} | |
interface ProviderState { | |
dispatch: any; | |
state: Partial<State>; | |
} | |
const initialState = { | |
selectedHealthCheck: undefined, | |
}; | |
const store = createContext<Partial<ProviderState>>({ | |
state: initialState, | |
}); | |
const { Provider } = store; | |
const StateProvider = ({ children }: any) => { | |
const [state, dispatch] = useReducer( | |
(state: Partial<State>, action: Action) => { | |
switch (action.type) { | |
case "select healthcheck": | |
return update(state, { | |
$set: { | |
selectedHealthCheck: action.payload, | |
}, | |
}); | |
case "fetched health": | |
return update(state, { | |
selectedHealthStatus: { $set: action.payload }, | |
}); | |
case "fetched details": | |
return update(state, { | |
selectedHealthDetails: { $set: action.payload }, | |
}); | |
default: | |
throw new Error(); | |
} | |
}, | |
initialState | |
); | |
return <Provider value={{ state, dispatch }}>{children}</Provider>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment