Skip to content

Instantly share code, notes, and snippets.

@psaia
Created August 7, 2020 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psaia/679c9e05ed6d7bd7ba5687ca283b0f41 to your computer and use it in GitHub Desktop.
Save psaia/679c9e05ed6d7bd7ba5687ca283b0f41 to your computer and use it in GitHub Desktop.
Redux style store without Redux.
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