1
votes

Trying to go through a simple Axios tutorial to start getting used to populating dynamic data. Loading and Using External Data in React

I had to create a JSON web server since hitting Codepen with localhost violated CORS.

App.jsx

var App = React.createClass({
  getInitialState: function(){
    return{
      users: []
    };
  },  
  componentDidMount: function(){
    var _this = this;
    this.serverRequest =
      axios
        .get("http://localhost:3004/users")
        .then(function(results){
          console.log(results.data);
          _this.setState({
            users: results.data.users
          });
         });
  },
  componentWillUnmount: function(){
    //...
  },
  render: function(){
    return(
        <div>
          <h3>Returning Users:</h3>
            {this.state.users.map(function(user) {
          return (
            <div>{user.name}</div>
          );
         })}
        </div>
    );
  }
});

export default App;

I understand that data should be extrapolated out into something like Redux but this is just a start to working with dynamic data. The error I'm getting is Uncaught (in promise) TypeError: Cannot read property 'map' of undefined I can't find very good explanations of this error doing some research. So what am I doing wrong?

I see that if I pre-populate data into the getInitialState I can get a return. So what is going wrong with the Promise getting data loaded into the initial state?

Edits:

Console.log Image:

enter image description here

2
What is the result of this line console.log(results.data);Abdennour TOUMI
I get a data return as expected. It looks like that data isn't being pushed into the user array in getInitialStatewsfuller
can you show the output of console.log(results.data); ?Mayank Shukla
I've added an image for the console outputwsfuller
is this the output of results.data or results.data.users ??Mayank Shukla

2 Answers

0
votes

If you see the result of your console output. It doesn't contain the `key users' and hence

 _this.setState({
        users: results.data.users
      });

will set the state users to undefined and hence you get an error when trying to use map

Change the setState to

 _this.setState({
        users: results.data
      });
1
votes

Its because the user state is empty initially, willmount method did nothing here,so it directly goes to render method and then goes to didmount, in render method it tries to map the user state with undefined value, that causes the error, i think you should check the user state is undefined or not. check it directly in render method or create a function for rendering the mapping. (suppose the method name is renderUser), then you can put the method fetching directly as {this.renderUser()}

Change your setState to this,

_this.setState({
    users: results.data
});