VersifiXion
VersifiXion

Reputation: 2292

Adding an object to an array (with Hooks in React)

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 !

Upvotes: 2

Views: 3323

Answers (4)

Use: const [mesages, setMessages] = useState([]);

Upvotes: 0

Ponpon32
Ponpon32

Reputation: 2200

This happen because the initial value of messages is boolean and you can't spread it into the new messages array.

Try:

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

Upvotes: 1

ibtsam
ibtsam

Reputation: 1710

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

Upvotes: 2

Davin Tryon
Davin Tryon

Reputation: 67336

Use a more appropriate default value (of the same type):

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

Then, you will always be able to spread messages.

Upvotes: 2

Related Questions