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
Effects run in order, so when you refresh the page the code you have here is going to
setItem
before yougetItem
.An alternative to your second
useEffect
there is to initialise youruseState
hook directly from thelocalStorage
:Yes the reason is
JSON.parse(localStorage.getItem("topic"))
gives you the string"undefined"
instead of the object undefined.Instead try doing