I have this todo app I made with redux but i wanna use localstorage, the thing is that don't know how to use it, I did some research but i got many errors like "todos.map is not a function" can you guys help me out? the "todos" is an array of objects for initial state
P.S: without the local storage it works well
store.js
export const store = createStore(
reducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
reducer.js
export const reducer = (state = todos, action) => {
let newTodos;
// eslint-disable-next-line default-case
switch (action.type) {
case ADD_TODO:
newTodos = [...state];
newTodos.push(action.payload);
return newTodos;
case DELETE_TODO:
newTodos = [...state];
newTodos = newTodos.filter((todo) => todo.id !== action.payload);
return newTodos;
case UPDATE_TODO:
newTodos = [...state];
let index = -1;
for (let i = 0; i < newTodos.length; i++) {
index++;
if (newTodos[i].id === action.payload.id) {
break;
}
}
if (index !== -1) {
newTodos[index] = action.payload;
return newTodos;
}
}
return state;
};
TodoList.js
const TodoList = () => {
const todos = useSelector((state) => state);
return (
<div>
{todos.map((todo) => {
return <Todo key={todo.id} todo={todo} />;
})}
</div>
);
};
export default TodoList;
localstorage.js
export function loadState() {
try {
const serializedState = localStorage.getItem("state");
if (serializedState === null) {
return undefined;
}
return JSON.parse(serializedState);
} catch (error) {
return undefined;
}
}
export function saveState(state) {
try {
const serializedState = JSON.stringify(state);
localStorage.setItem("state", serializedState);
} catch (error) {
alert(`Error while saving state: ${error.message}`);
}
}