2

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
  • Change this setListArray([...listArray].push(myNewList)); to setListArray([...listArray, myNewList]); Commented May 28, 2021 at 18:50

1 Answer 1

2

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]);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the details and works. Just one thing, which type should I use in place of <any> in the state declaration?
@Mugi I'm not super familiar with Typescript, but from what I can tell, maybe useState<newList []>([]); if I haven't bunged up the syntax, in other words, it's an array of newList types, i.e. newList[]. Looks like useState<Array<newList>>([]); may also work. typescriptlang.org/docs/handbook/2/everyday-types.html#arrays

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.