Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

78
Views
React with TypeScript - LocalStorage won't work

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?

7 months ago · Juan Pablo Isaza
2 answers
Answer question

0

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]
}
7 months ago · Juan Pablo Isaza Report

0

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) : [];
});
7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs