2

I'm working on a simple React web app and I'm having problem viewing certain data I'm pulling from this mock api: https://randomuser.me/api/

Here is my code:

import React, { Component } from 'react';

class ApiTest extends Component {
    constructor() {
      super();
      this.state = {
        names: [],
      };
    }

    componentDidMount() {

  fetch('https://randomuser.me/api/?results=10')
  .then(results => {
    return results.json();
  }).then(data => {
    let names = data.results.map((name) => {
      return(
        <div key={name.results}>
           {name.title}
        </div>
      )
    })
    this.setState({names: names});
    console.log("state", this.state.names);
  })
}

  render() {
      return (
        <div className="App">

          <div className="container2">
            <div className="container1">
              {this.state.names}   
            </div>
          </div>

        </div>
      );
    }
  }

  export default ApiTest;

I am able to pull in the pictures based off the tutorial I found for all of this (https://blog.hellojs.org/fetching-api-data-with-react-js-460fe8bbf8f2) but I can't seem to get anything else to display. I don't seem to be getting any errors and I see these objects in the console. What am I doing wrong here? Thanks guys!!!

1 Answer 1

1

it's really not a very good idea to put jsx into your component state. State should consist of plain data. Then you can transform you data in a flexible manner inside render() function:

https://codesandbox.io/s/qqy9l78l06

import React, { Component } from "react";

class ApiTest extends Component {
  constructor() {
    super();
    this.state = {
      people: []
    };
  }

  componentDidMount() {
    fetch("https://randomuser.me/api/?results=10")
      .then(results => results.json())
      .then(data => this.setState({ people: data.results }));
  }

  render() {
    console.log(this.state);
    return (
      <div className="App">
        <div className="container2">
          <div className="container1">

            {this.state.people.map(person => (
              <div>{person.name.first}</div>
            ))}

          </div>
        </div>
      </div>
    );
  }
}

export default ApiTest;
Sign up to request clarification or add additional context in comments.

3 Comments

Is this why you separated the code into .js and .jsx files? Thanks! this seems to work perfectly.
Hi! No separation has nothing to do with the fact that it works :-) Actually on codesandbox .js and .jsx files are equaly, but usually only .jsx files are expected to have jsx code in them.
I tick'd it but I guess if you have less than 15 rep it doesn't visually change. Thanks for your help!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.