Skip to content

Commit

Permalink
Merge pull request #33 from KcPele/persistent-data
Browse files Browse the repository at this point in the history
changed data persistance
  • Loading branch information
escottalexander authored Aug 22, 2023
2 parents 4885a97 + 3126f1c commit 84e6841
Showing 1 changed file with 10 additions and 5 deletions.
15 changes: 10 additions & 5 deletions packages/nextjs/context/BallotContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { ReactNode, createContext, useContext, useReducer } from "react";
import { useLocalStorage } from "usehooks-ts";

// Interface for project to be added to the ballot
interface Project {
Expand Down Expand Up @@ -154,17 +153,23 @@ const reducer = (state: State, action: Action): State => {
// Provider component
export const BallotProvider: React.FC<BallotProviderProps> = ({ children, totalTokens }) => {
const [state, dispatch] = useReducer(reducer, { projects: [], totalTokens, importedLists: [] });
const [loadedState, setLoadedState] = useLocalStorage("ballotState", JSON.stringify(state));

// Load state from local storage on initial render
React.useEffect(() => {
if (loadedState) {
dispatch({ type: "LOAD_STATE", stateData: JSON.parse(loadedState) });
const localStorageBallot = localStorage.getItem("ballotState");
if (localStorageBallot) {
const ballotData = JSON.parse(localStorageBallot) as State;
if (ballotData.projects?.length) {
dispatch({ type: "LOAD_STATE", stateData: JSON.parse(localStorageBallot) });
}
}
}, []);

// Update local storage whenever the state changes
React.useEffect(() => {
setLoadedState(JSON.stringify(state));
if (state.projects.length || state.importedLists.length) {
localStorage.setItem("ballotState", JSON.stringify(state));
}
}, [state]);

return <BallotContext.Provider value={{ state, dispatch }}>{children}</BallotContext.Provider>;
Expand Down

0 comments on commit 84e6841

Please sign in to comment.