How to persist chat messages in React?

  javascript, reactjs

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

Source: Ask Javascript Questions

LEAVE A COMMENT