Andrea D_
Andrea D_

Reputation: 2141

Destructuring an object with useState

I am getting this Error:

Unhandled Rejection (TypeError): object is not iterable (cannot read property Symbol(Symbol.iterator))

when destructuring ...vaults (object) inside setVaults.

Code:

  const [vaults, setVaults] = useState();

  const name = 'something'
  const totalSupply = 155000
  const totalBorrowed = 55050
  const capUtilRate = 0
  setVaults(...vaults, {[name]: {totalSupply, totalBorrowed, capUtilRate}})

Why is this happening?

Upvotes: 1

Views: 1568

Answers (1)

Drew Reese
Drew Reese

Reputation: 203587

Initial state is undefined, and thus, not iterable. It seems your state is an object. You should use a functional state update as well. Remove the curly brackets around the property you are trying to set.

const [vaults, setVaults] = useState({});

...

const name = 'something';
const totalSupply = 155000;
const totalBorrowed = 55050;
const capUtilRate = 0;

setVaults(vaults => ({
  ...vaults, // <-- spread previous state
  [name]: {  // <-- create new object reference
     totalSupply,
     totalBorrowed,
     capUtilRate,
  },
}));

Upvotes: 2

Related Questions