skip to Main Content

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.

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);
   }
}, []);

2

Answers


  1. 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) : [];
        });
    
    Login or Signup to reply.
  2. Yes the reason is JSON.parse(localStorage.getItem("topic")) gives you the string "undefined" instead of the object undefined.
    Instead try doing

    useEffect(() => {
       let topics = localStorage.getItem("topic");
       if (topics) {
         topics = JSON.parse(topics)
         setTopic(topics);
       }
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search