diff --git a/src/app/store.js b/src/app/store.js index 3a66dd0..c5a7218 100644 --- a/src/app/store.js +++ b/src/app/store.js @@ -1,8 +1,17 @@ import { configureStore } from "@reduxjs/toolkit"; import boardReducer from "../storeSlices/boardSlice"; +import { saveState } from "../utils/persistStateUtils"; -export default configureStore({ +const store = configureStore({ reducer: { board: boardReducer } }); + +// Save state in localStorage, on save +// Loading code in reducers +store.subscribe(() => { + saveState(store.getState()); +}); + +export default store; diff --git a/src/storeSlices/boardSlice.js b/src/storeSlices/boardSlice.js index 112fd98..f5969df 100644 --- a/src/storeSlices/boardSlice.js +++ b/src/storeSlices/boardSlice.js @@ -1,5 +1,10 @@ import { createSlice } from "@reduxjs/toolkit"; + import generateID from "../utils/generateID"; +import { loadState } from "../utils/persistStateUtils"; + +const existingStore = loadState(); +let existingBoardSlice = (existingStore && existingStore.board) || {}; export const slice = createSlice({ name: "board", @@ -34,7 +39,9 @@ export const slice = createSlice({ } ] } - ] + ], + // Overwrite with existing localStorage stuff + ...existingBoardSlice }, reducers: { // NOTE: Modifying state directly here is FINE and intended. @@ -81,7 +88,9 @@ export const slice = createSlice({ const { text: cardText, cardID, listID: parentListID } = action.payload; const parentList = state.lists.find(({ id }) => id === parentListID); - const existingCardIndex = parentList.cards.findIndex(({ id }) => id === cardID); + const existingCardIndex = parentList.cards.findIndex( + ({ id }) => id === cardID + ); if (existingCardIndex > -1) { parentList.cards.splice(existingCardIndex, 1); @@ -90,6 +99,12 @@ export const slice = createSlice({ } }); -export const { createList, createTask, editList, editTask, deleteTask } = slice.actions; +export const { + createList, + createTask, + editList, + editTask, + deleteTask +} = slice.actions; export default slice.reducer; diff --git a/src/utils/persistStateUtils.js b/src/utils/persistStateUtils.js new file mode 100644 index 0000000..d11576e --- /dev/null +++ b/src/utils/persistStateUtils.js @@ -0,0 +1,24 @@ +// Taken from https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/saving-redux-state-to-local-storage +export const loadState = () => { + try { + const serializedState = localStorage.getItem('reduxAppState'); + + if (serializedState === null) { + return undefined; + } + + return JSON.parse(serializedState); + + } catch (err) { + return undefined; + } +}; + +export const saveState = (state) => { + try { + const serializedState = JSON.stringify(state); + localStorage.setItem('reduxAppState', serializedState); + } catch (err) { + // die + } +};