1
I’m trying to create several components <Pit />
however, one per result coming from the API, without excluding the previously created.
The API returns an object with 2 arrays inside, the solution was to put each array into a state variable and pass as props directly to the Pit component.
However, this way I can create only 1 Pit component and each API return overwrites the previous one...
My code is like this:
myCallback = (dataFromChild) => {
this.setState({cod_ativo_search: dataFromChild});
this.callApi(dataFromChild);
}
async callApi(dataFromChild) {
const response = await api.get(`/ativo/ativo?cod_ativo='${dataFromChild}'`);
if(response.data[0].valueOf().rows.length != 0 || response.data[1].valueOf().rows.length != 0){
this.setState({ responseCompra: response.data[0].rows })
this.setState({ responseVenda: response.data[1].rows })
this.setState({ codAtivo: dataFromChild })
}
}
render() {
return (
<div>
<SearchBar callbackFromParent={this.myCallback}/>
<Pit responseCompra={this.state.responseCompra} responseVenda={this.state.responseVenda} codAtivo={this.state.codAtivo} />
</div>
);
}
Any idea how I can create an array and insert each new result coming from the API to create several Pit components?
Place an array of <Pit> data in the state:
const dado = {compra: response.data[0].rows, venda: response.data[1]....}; { dados } = this.state; dados.push(dado); this.setState(state => ({state, dados: dados}));
. Use a loop to create the Pit:{ dados } = this.state; const pits = dados.map(d => <Pit responseCompra={d.compra}... />); return (<div>{pits}</div>);
– mari
@But the part of creating several Pits worked, but to work I had to do so:
const dado = {compra: this.state.responseCompra, venda: this.state.responseVenda}; 
this.state.dados.push(dado);

const pits = this.state.dados.map(d => <Pit responseCompra={d.compra} responseVenda={d.venda} />);
Onlydados
in state is duplicating and creating duplicate cards, follows image of how is getting duplicated state state_duplicated What is wrong?– dev-john
@Mari found a solution, your reply helped a lot, write in the reply to mark as solution please, I add what I did in the comment.
– dev-john