Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

localStorage not properly saving array in React

Working on a forum and I need my topics to start not erasing upon refresh so that I can start checking whether or not the messages display properly.

I have it so each time I make a topic, the topic is stored as an object inside an array. Each object stores different types of information like the title of the topic, the message, the author and the date. The array is then sorted and mapped and displays all the information on the page.

The addTopic function is used as an onClick for a form that pops up.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have my localStorage set up using a useEffect like it was suggested however every time I make a topic and refresh the page, the array still erases itself and I’m back to the original state. Please advice.

const [topic, setTopic] = useState([]);
    
const [title, setTitle] = useState();
const [message, setMessage] = useState();
    
const addTopic = (e) => {
   e.preventDefault();
    
   const updatedTopic = [
     ...topic,
     {
       title: title,
       message,
       author: "Dagger",
       date: new Date(),
       },
    ];
    
   setTopic(updatedTopic);

};
    
useEffect(() => {
   localStorage.setItem("topic", JSON.stringify(topic));
 }, [topic]);
    
useEffect(() => {
   const topics = JSON.parse(localStorage.getItem("topic"));
   if (topics) {
     setTopic(topic);
   }
}, []);

>Solution :

Effects run in order, so when you refresh the page the code you have here is going to setItem before you getItem.

An alternative to your second useEffect there is to initialise your useState hook directly from the localStorage:

  const [topic, setTopic] = useState(
    () => {
      const topicJson = localStorage.getItem("topic");
      return topicJson ? JSON.parse(topicJson) : [];
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading