score:9

Accepted answer

Instead of this:

      res.data.map((item) => {
        const joined = this.state.marca.concat([
          { name: item.name, id: item.id },
        ]);
        this.setState({ marca: joined });
      });

Do this:

      res.data.map((item) => this.setState(prevState => {
        const joined = prevState.marca.concat([
          { name: item.name, id: item.id },
        ]);
        return({ marca: joined });
      }));

You're not supposed to directly or indirectly reference this.state in what you eventually pass to this.setState.

score:2

If you have to mutate the state (e.g. adding an item) then you can pass a function to setState that receives the previous and returns the next state:

  this.setState(previousState => ({ marca: [...previousState.marca, { name: item.name, id: item.id }] }));

It will be way faster to add all items at once though:

 this.setState(previousState => ({
   marca: [
    ...previousState.marca,
    ...res.data.map((item) => ({ name: item.name, id: item.id }))
   ],
 }));

Related Query

More Query from same tag