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

react hooks usestate array
react hooks update array of objects
push data into array react
react update state array of objects
react hooks usestate object
react hooks onchange array
react array of objects
react setstate array not working

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 !

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

Push method in React Hooks (useState)?, Pass wrapper function to state setter function (as a call-back function) Your state is an array so you will need to spread your previous state into a new array and add the new message using [prevState, newMessage] What you try to do is return an object, because {} is a code block so you need to wrap it inside if you return an object which is what you are trying to do

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

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

Then, you will always be able to spread messages.

Dynamically Add Values in String Array List in React Native on , using . concat or spread … inside the wrapper function. A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components. We’ll learn other Hooks later. When would I use a Hook? If you write a function component and realize you need to add some state to it, previously you had to convert it to a class.

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([]);

How can I use React hooks in React classic `class` component , then, when you want to add a new element, you use that function and pass in the new array or Push/update element at end of array of objects React Hooks Add To Array React Hooks Add To Array That said, Redux works especially well with libraries like React and Deku because they let you describe UI as a function of state, and Redux emits state updates in response to actions. First we have to set the key, and then specify the data object.

React useEffect : A hook to introduce lifecycle methods in functional , How do you add an object to an array in react native? React hooks useState Array. Ask Question add a comment | Is spacetime curved in a near-earth-free-falling-object's frame of reference?

React Hooks Tutorial - 5 - useState with array, React Hooks Tutorial - 4 - useState with object - Duration: 7:19. Codevolution 60,487 views Duration: 5:55 Posted: May 20, 2019 While the array from the previous state is spread into a new array, so the previous arrays doesn't get mutated, the new item is added at the end of the array. Now, you can add the item at the start of the array by using const list = [state.value, state.list]; instead. React State: Update item in array

4 Examples of the useState Hook, There are a bunch of React hooks, but useState is the workhorse of the bunch. cover useState with simple types, as well as useState with objects and arrays. The useState hook lets you add state to function components. Generally you should watch out for deeply nested objects in React state. To avoid unexpected behavior, the state should be updated immutably. When you have deep objects, you end up deep cloning them for immutability, which can be quite expensive in React.

Comments
  • Please show all the relevant code. where is messages created? What is its default value?
  • This works if messages is created as en empty array. let array = []; array = [...array, 'Hi'];
  • @DavinTryon messages default value is "false", and becomes an array with datas after the loadMessages() in the useEffect. I just added some code
  • @sebastienbarbier messages default value is "false", but after the function loadMessages is executed in the useEffect, it becomes an array with objects inside
  • It is an issue of incorrect typings. You should not assign it to false, even if you eventually assign it to an array. You are trying to spread/iterate a boolean value instead of an object/array. Use this instead: const [messages, setMessages] = useState([]);
  • great, if it helped you feel free to up vote and accept the answer, cheers
  • Now all you need to do is to accept this amazing answer, slowly move your mouse to the check sign, click on it. @Versifiction