When creating a component I make a query to an api where I bring a table with information, when passing this information to another component as props, it receives it correctly but I cannot assign it as state
Here I create the component, I make the query
import React, { Component } from "react";
import Table from './table/Table';
class Busqueda extends Component {
constructor(props){
super (props);
this.state={
data:[{}]
}
}
componentWillMount = async()=>{
const response = await fetch (`http://localhost:4000/autores`);
const columns=await response.json()
this.setState({
data:columns.datos
});
}
render() {
return (
<div>
<Table data={this.state.data}></Table>
</div>
);
}
}
export default Busqueda;
Here I receive the prop but I can't get it to be assigned as a state
import React, { Component } from "react";
class Table extends Component {
constructor(props){
super (props);
this.state={
data:this.props.data
}
}
render() {
return (
<div>
<table className="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">Nombre</th>
</tr>
</thead>
<tbody>
{this.state.data.map((elemento,i) => (
<tr key={i}>
<th scope="row">{elemento.id}</th>
<td >{elemento.nombre}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default Table;
Image: https://i.stack.imgur.com/YzQZj.png
CodePudding user response:
It's because you are assign props once, on init. To listen on that changes you should use componentDidUpdate method.
Or just use props to render table rows. I strongly suggest to rethink dataflow, in my opinion Table should be stateless.