React Typescript trying to change state of an array objects resulting in error

Viewed 69

I am new to Typescript and I try to push a new object to the array In React state but I'm getting the following error:

Type '{ name: string; address: string; }[] | null' is not an array type.ts(2461)
const info: {
    name: string;
    address: string;
}[] | null

here is the code:

interface StateProps {
  info: {
    name: string;
    address: string;
  }[];
}


function App() {
  const [info, setInfo] = useState<StateProps["info"] | null>(null);

  const nameHanlder = () => {
//the editor highlight ...info as an error
    setInfo([...info, { name: "foo", address: "bar" }]);
  };

  return (
    <div className="App">
      <p></p>
      <button onClick={nameHanlder}>add name</button>
    </div>
  );
}

1 Answers

info also could be null, that's why you are getting the error. You could check, that info is an array.

  const nameHanlder = () => {
    if (Array.isArray(info)) {
      setInfo([...info, { name: 'foo', address: 'bar' }])
    }
  }
Related