How to push an object in an array, using react hooks and typscript?

Viewed 287

I know this is completely a noob question and I'm sorry but I try to figure out how should I manage to put the Object in the state array when submitting the form. Thank you

interface newList {
  name: string;
}

const ListAdder = () => {
  const [listName, setListName] = useState("");
  const [listArray, setListArray] = useState<any>([]);

  const submitHandler = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();

    const myNewList: newList = {
      name: listName,
    };

    setListArray([...listArray].push(myNewList));
    setListName("");
    console.log(listArray);
  };

  const listNameHandler = (e: FormEvent<HTMLInputElement>) => {
    setListName(e.currentTarget.value);
  };

  return (
    <>
      <form onSubmit={submitHandler}>
        <label>Create your List</label>
        <br />
        <input
          type="text"
          placeholder="List name is..."
          value={listName}
          onChange={listNameHandler}
        />
        <button type="submit">Add the List</button>
      </form>
    </>
  );
};
1 Answers

The issue is that you are saving the result of the push, the new length, instead of the updated array.

setListArray([...listArray].push(myNewList)); // <-- saves result of push, [].length

You can concat the new element:

setListArray([...listArray].concat(myNewList));

Or just append it

setListArray([...listArray, myNewList]);

Additional semi-related issue, you can't console log the state and expect to see it immediately updated.

setListArray([...listArray, myNewList]);
console.log(listArray); // <-- still current state

React state updates are asynchronous, so logging the state like this will only ever log the state from the current render cycle and not the enqueued state for the next render cycle. If you want to log state after an update use an useEffect hook with dependency.

useEffect(() => {
  console.log(listArray);
}, [listArray]);
Related