1

I'm not sure what I'm doing wrong or what I'm missing but I can't iterate over my array of objects when I do my get request. I get the results on my console but they don't appear on the page unless I call one individual item. It only happens when I'm using React, I have also tried with JSON placeholder fake APIs and get the same result. Is there anything in React that stops this iteration to be executed? Thank you so much for your help!

import React, { Component } from 'react';

class UserList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [],
      isLoaded: false,
    };
  }

  componentDidMount() {
    this.loadData();
  }

  loadData = async () => {
    const response = await fetch('http://dev.pubmate.io/pubmate/api/0.1/user/all');
    if (response) {
      const allusers = await response.json();
      console.log(response);
      console.log(allusers);
      console.log(allusers[0].email);
      this.setState({
        isLoaded: true,
        users: [...allusers],
      });
    }
  };

  render() {
    let { isLoaded, users } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div className="userlist">
          Data is been loaded
          <ul>
            {users.map((user) => {
              <li key={user.id}>{user.title}</li>;
            })}
          </ul>
        </div>
      );
    }
  }
}

export default UserList;
1
  • You don't return anything from the callback function of .map(), hence nothing gets rendered. {users.map(user => <li key={user.id}> {user.title} </li>)} Commented Jan 15, 2021 at 14:03

1 Answer 1

1

You were quite close, but just need to slightly adjust your loop.

The simplest change would be to swap:

<ul>
  {users.map(user => {
    <li key={user.id}>
      {user.title}
    </li>
  })}
</ul>

for

<ul>
  {users.map(user => ( // <--- "{" becomes "("
    <li key={user.id}>
      {user.title}
    </li>
  ))} // <--- "}" becomes ")"
</ul>

This will return an element to be rendered

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

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.