0

My object is create an array of object as follows [{},{},{}]

State variable constructor like this:

this.state:{...some states,
            parsed:[{}]}

Every object come from get IPFS with async function:

 IPFSREADER = element => {
  ipfs.cat(convertedIPFSaddress).then(result => {
      let cons = result.toString('utf8')
      const consdata = JSON.parse(cons);
      // NEED useState save consdata to parsed state
}

When I get data, I am pushing this data to state with useState, but I tried as follows way:

  1. this.setState({parsed:consdata}) result: > Object:{some data...}

  2. this.setState({...[parsed],parsed:[consdata]}) result: [0:Object:{some data...}]

    • When there is a new data coming from ipfs, this only changes data, where is into the array, but doesn't append to tail of previous data.
  3. this.setState(parsed => [...data, parsed]); follow Joseph D.'s answer, but throw ReferenceError: can't access lexical declaration 'data' before initialization error. Try this solution changed above function as follows:

    • changed the function to async: IPFSREADER = async element => {..
    • added await in front of ipfs.cat: const { data } = await ipfs.cat(...

How can solve this problem? I tried many solutions, but can't change the result... Thanks.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Ekestfa
  • 38
  • 6
  • Does this answer your question? [Correct modification of state arrays in ReactJS](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) – Emile Bergeron Apr 30 '20 at 20:32

1 Answers1

0

It looks like you are trying to do setState({...state, parsed: [...state.parsed, consdata]})

Brad Fellows
  • 171
  • 8