0

I've spent a long time trying to figure out what is the exact problem. I have a react component that fetches an array of users from a service then store it in the component state but I had hardcode it here for simplicity. when I run my page nothing shows up with no signs of errors in the console. I'm a newbie to react please bear with me.

here is my component :

var usersTable = React.createClass({
      getInitialState: function() {
        this.state = {
          users: [],
          dataResponse: []
        };

        return this.state;
      },
      getData: function() {

        component.state.dataResponse.push({
          name: "john doe",
          email: "john.d@outlook.com",
          job: "production manager",
          id: 882771
        });

        component.state.dataResponse.push({
          name: "jane doe",
          email: "jane.d@outlook.com",
          job: "account manager",
          id: 569811
        });
        //get the users from a service.

      },
      componentWillMount: function() {
        this.getData();

        if (this.state.dataResponse !== null && this.state.dataResponse !== undefined) {
          var data = this.state.dataResponse;

          for (var i = 0; i < data.length; i++) {
            var tr = <tr>
              <td> {
                data[i].id
              } </td> <td> {
                data[i].name
              } </td> <td> {
                data[i].job
              } </td> <td> {
                data[i].email
              } </td> </tr>;
            this.state.users.push(tr);
          }
        }
      },
      render: function() {
        return ( <table className = "table table-condensed"> {
            this.state.users
          } </table>);
        }
      });

    ReactDOM.render( <usersTable /> , document.getElementById("usersComponentDiv"));

Plunk : https://plnkr.co/edit/CyYCgTArt7K5MLAbiCa7?p=preview

Voice Of The Rain
  • 495
  • 1
  • 8
  • 24
  • I am not sure if this is the issue. But one thing to think about is the arrays you have in your state are immutable. So if you want to update the value you have to replace the entire array with a new instance, you cannot do `component.state.dataResponse.push`. Read [this answer](https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs) for further guidance on the best way to update state arrays component.state.dataResponse.push – Michael Hancock Jan 24 '18 at 08:23
  • You should not mutate the state directly, use setState instead check this https://stackoverflow.com/questions/45187529/is-there-any-other-way-to-avoid-react-forceupdate/45187565#45187565 – Shubham Khatri Jan 24 '18 at 08:40

1 Answers1

1

In order to change your component's state, use:

this.setState({
  users: [...]
})

or

this.setState({
  dataResponse: [...]
})

trying to use as this.state.users.push(..) or this.state.dataResponse.push(...) is not going to work.

I also noticed you are using state to save HTML markup (such as td and tr) and this is not a good pattern due to performance reasons. It's better to keep only an array of objects with id, name, job and email only.

Remember that setState is asynchronous and you will not have access to state's latest value right away if you try as:

this.setState({
  users: [{ id: 1 }, { id: 2 }]
})

this.state.users // outdated version

Should you need access to its latest value, rather use:

this.setState({
  users: [{ id: 1 }, { id: 2 }]
}, () => {
  console.log(this.state) // new state version
})

In case you also need to access old state before update the new one, you also have the option:

this.setState(prevState => ({
  users: [...prevState.users, { id: 3 }, { id: 4 }],
}), () => {
  console.log(this.state) // new state 
})
Hemerson Carlin
  • 7,354
  • 1
  • 27
  • 38