Ad

Adding An Object To An Array (with Hooks In React)

- 1 answer

I want to add an object to an array in React using Hooks, I'm doing a chat, and I want to add a new message to the array of messages,

I tried this :

setMessages([...messages, newMessage]);

Here is more of the code :

const [messages, setMessages] = useState(false);

useEffect(() => {
    socket.open();

    loadMessages();

    return () => {
      socket.close();
    };
  }, []);

useEffect(() => {
    socket.on("send message", data => {
      setMessages([...messages, data]);
    });

    socket.on("delete message", data => {
      setMessages(messages.filter(message => message.id !== data.id));
    });
  });

async function loadMessages() {
    try {
      const dataMessages = await axios.get(
        `http://localhost:5000/api/chat/messages`
      );
      setMessages(dataMessages.data);
    } catch (error) {
      console.log(error);
    }
  }

but I got the TypeError: "messages is not iterable",

can someone help me? thank you !

Ad

Answer

You are setting messages as boolean value Change this

const [messages, setMessages] = useState(false);

to

const [messages, setMessages] = useState([]);

Then add elements to array, also dont mutate the messages array.

Hope it helps

Ad
source: stackoverflow.com
Ad