In a chat application built in React, my intention is store the chat messages in localStorage. Following is the code for your reference
const [textMessages, setTextMessages] = useState([]);
const [textValue, setTextValue] = useState('')
useEffect(() => {
localStorage.getItem('messages') // Doesn't load the stored data
}, []);
const sendMessage = (e) => {
e.preventDefault();
if (textValue != "") {
const newData = []
newData.push([...textMessages, textValue])
setTextMessages([...textMessages, textValue]);
localStorage.setItem('messages', JSON.stringify(newData))
setTextValue("");
} else {
return;
}
};
return (
<>
<button type="submit" onClick={sendMessage}>
Send Message
</button>
</>
)
What could be the best solution? Here is the codesandbox link: https://codesandbox.io/s/upbeat-montalcini-bpdsp
You need to parse the JSON string back into an array, and set your state:
useEffect(() => {
const savedMessages = JSON.parse(localStorage.getItem('messages'))
if (savedMessages !== null) {
setTextMessages(savedMessages)
}
}, []);
Other things that are worth thinking about but I won't include in the simple example:
JSON.parse()
in a try-catch, just in case the user has modified their local storage and it is now invalid JSON.const storageKey='messages'; localStorage.getItem(storageKey)
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.