0

I am new to react and started looking into pulling json data in. To test I am using: https://randomuser.me/api/?results=5

What I am trying to achieve is when I click on a username from json, it will console log the username. How do I pass the value from json to console log?

const API = 'https://randomuser.me/api/?results=5';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      logins: [],
    };
  }

  componentDidMount() {
    fetch(API)
      .then(response => response.json())
      .then(data => {
        let logins = data.results.map((uname) => {
          return (
            <div>
              <button>{uname.login.username}</button>
            </div>
          )
        })
        this.setState({logins: logins});
      })
  }

  render() {
    return (
      <div>
        {this.state.logins}
      </div>
    );
  }
}

Is it a good idea to return html code in componentDidMount or should I leave it to render?

2
  • No, move out the html code from the componentDidMount(). Commented Apr 25, 2018 at 14:19
  • And as for first question: "How do I pass the value from json to console log?" - you can pass to console.log whole JSON or particular field using dot operator. console.log is very smart about printing whole JSON objects Commented Apr 25, 2018 at 14:21

2 Answers 2

1

You can do what you like, but typically you'd leave component creation (it's not really HTML) to render:

const API = 'https://randomuser.me/api/?results=5';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      logins: [],
    };
  }

  componentDidMount() {
    fetch(API)
      .then(response => response.json())
      .then(data => {
        this.setState({logins: data.results});
      })
  }

  render() {
    return (
      <div>
        {this.state.logins.map((uname) => (
            <div>
              <button>{uname.login.username}</button>
            </div>
        ))}
      </div>
    );
  }
}

state should typically hold data, and leave the rendering of that data to render.


Side note: Your fetch call is missing two things:

  1. A check for ok status, and

  2. An error handler

    fetch(API)
      .then(response => {                             // ***
        if (!response.ok) {                           // ***
          throw new Error({status: response.status}); // ***
        }                                             // ***
      })                                              // ***
      .then(response => response.json())
      .then(data => {
        // ...
      })
      .catch(err => {                                 // ***
        // Handle the error                           // ***
      });                                             // ***
    

fetch doesn't reject on status errors like 404.

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

Comments

0

Actually you can do whatever you want, but for reading/usage purposes, it would be better to have all the html on the render. so changing your code should be like:

const API = 'https://randomuser.me/api/?results=5';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      logins: [],
    };
  }

  componentDidMount() {
    fetch(API)
      .then(response => response.json())
      .then(data => {
        let logins = data.results.map((uname) => {
          return uname.login.username;
        })
        this.setState({logins: logins});
      })
  }

  render() {
    return (
      <div>
      {
          this.state.logins.map(u=> {
              <div>
                  <button>{u}</button>
              </div>
          })
      }
      </div>
    );
  }
}

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.