Logesh P
Logesh P

Reputation: 227

Add an item to array - reactjs hooks

I am trying to add an item to the array. That array was fetched using an API.

but when I click to add the item, it's not updating.

here is my onChange code

  const changeHandler = e => {
    e.preventDefault();
    const textName = e.target.value;
    setText(textName);
  };

here is my add to array code

  const addNewHandler = e => {
    e.preventDefault();
    const addNewname = {
      id: Math.random().toString(),
      name: text
    };

    console.log(addNewname);
    const apiupdate = [...api];
    // apiupdate.concat(addNewname);
    // console.log(apiupdate);
    setApi(apiupdate.concat(addNewname));
    console.log(api);
  };

here is where I call that function

<TextField
  variant="outlined"
  value={api.Name}
  name="Name"
  onChange={changeHandler}
/>
<Button
  variant="outlined"
  color="primary"
  style={{ margin: "10px" }}
  onClick={addNewHandler}
>
  Add Me
</Button>

https://codesandbox.io/s/suspicious-hooks-swvn0...

Please use this in your local network issue with fetch when using in the sandbox

Upvotes: 1

Views: 95

Answers (1)

Fred
Fred

Reputation: 3441

Change your code like this:

const addNewHandler = e => {
    e.preventDefault();
    const addNewname = {
       id: Math.random().toString(),
       nutritionalInformation: {
         calories: 0,
         fat: 0,
         saturatedFat: 0,
         sugars: 0,
         salt: 0
      },
      name: text
    };

    console.log(addNewname);
    const apiupdate = [...api, addNewname];
    // apiupdate.concat(addNewname);
    // console.log(apiupdate);
    setApi(apiupdate);
    console.log(api);
};

[...api, addNewname] add addNewname to end of api array and make a new array.

Also, I set nutritionalInformation when adding new item.

Upvotes: 1

Related Questions