Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

State does not save ReactJS

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading