I am working with persistence on a todo application written with React and TypeScript. I am using localStorage to get the persistence I want.
Let me show you some code.
const [todos, setTodos] = useState<todoModel[]>([]);
useEffect(() => {
localStorage.setItem("todoItem", JSON.stringify(todos));
}, [todos])
const storesTodos = () => {
const storedValues = localStorage.getItem("todoItem");
if(!storedValues) { return todos; }
return JSON.parse(storedValues);
}
useEffect(() => { getToDoList(); storesTodos();
console.log("default") }, [])
useEffect(() => {
if (!props.reload) return;
console.log(props.reload)
getToDoList();
storesTodos();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.reload])
I am adding the StoresTodo()
function into my useEffects, I tried both of them.
But it won't work. I get the data into my localStorage, but when reloading the page, it gets back to default values.
What am I missing here?
It seems like you are getting the same initial value because you never update the todos
, judging based on shared code.
You can do this
...
const storesTodos = () => {
const storedValues = localStorage.getItem("todoItem");
if(!storedValues) {
setTodos(todos)
return todos;
}
return JSON.parse(storedValues);
}
Or you can use a local storage state hook from here
function useLocalStorageState({
key,
initialValue,
serialize = v => v,
deserialize = v => v,
}) {
const [state, setState] = React.useState(
() => deserialize(window.localStorage.getItem(key)) || initialValue,
)
const serializedState = serialize(state)
React.useEffect(() => {
window.localStorage.setItem(key, serializedState)
}, [key, serializedState])
return [state, setState]
}
When you refresh the page, even before the useEffect sets in
const [todos, setTodos] = useState<todoModel[]>([]);
already will set your initial todos array to an empty array.
Perhaps you'll need to perform the check on localStorage on it like so
const [todos, setTodos] = useState<todoModel[]>(() => {
const storedValues = localStorage.getItem("todoItem");
return storedValues ? JSON.parse(storedValues) : [];
});