0

I am getting an error that says "TypeError: this.state.users.map is not a function" however there is a list variable in my state which is binded so I am not sure why the map function is not working.

      getList(){
        console.log("FUNCTION CALLED");
        axios.get("/api/mentorRequests")
        .then((result) => {
          console.log("Logging results", result);
          this.setState({users: result});
        })
      }
      render() {
        console.log("USERS", this.state.users);
        return (
          <div className="">
               {this.state.users.map((user) => 
                <div>
                  {user.displayName}
                </div>
              )}
          </div>
        );
      }
1
  • Please provide more information. map() is an array method, so the possible issue is your users state is not an array. try to initialize users state with an empty array and check the result you get from getList() is an array. Commented Nov 14, 2020 at 2:21

4 Answers 4

2

You should check and see if the response you are getting is an array because .map is array function you cant use it on something else so it'll give you TypeError because type of the object you are trying to use .map is not right.

Sign up to request clarification or add additional context in comments.

Comments

2

You might forget to initialize state.users with an empty array.

this.state = {
  users: []
}

Comments

1

Try to do the following:

getList() {
   console.log("FUNCTION CALLED");
   axios.get("/api/mentorRequests")
   .then((result) => {
      console.log("Logging results", result);
      this.setState({users: result});
   })
}
render() {
   console.log("USERS", this.state.users);
   return (
     <div className="">
        {this.state.users && this.state.users.map((user) => 
            <div>
               {user.displayName}
            </div>
        )}
     </div>
   );
}

Comments

0

My function getList() was returning a json object and I was setting the array in my state to the json object so there was a type mismatch. Thanks to everyone who helped.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.