0

I want fetch a json api and push that result into an array:

import React from 'react';
import ReactDOM from 'react-dom';

function Users(){

    const url = 'https://randomuser.me/api/?results=5';
    let nodes = [];

    fetch(url)
    .then(response => {
        return response.json();
    })
    .then(j => {
        for( var i = 0; i <= j.results.length; i++ ){
            nodes.push(<li>{j.results[i].name.first}</li>);
        }
    });

    return(
            <ul>{nodes}</ul>
    );

}

ReactDOM.render(
    <Users />,
    document.getElementById('main')
);

But I have the following error in the console:

TypeError: j.results[i] is undefined

How can I fixed this error?

2
  • 1
    The error is because of small comparison mistake, i <= j.results.length; should be i < j.results.length; but you structuring is not correct Commented Dec 20, 2017 at 9:09
  • @ShubhamKhatri i edited , but i have not any result, so what's the right way for repeating json result in react ?! Commented Dec 20, 2017 at 9:19

2 Answers 2

1

I'm not sure that this is react way of fixing this problem. Here is the solution of your problem:

class Hello extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      nodes: []
    }
  }

  componentDidMount(){
    this.fetchData();
  }

  fetchData(){
    console.log('here')
    const url = 'https://randomuser.me/api/?results=5';
    fetch(url)
      .then(response => response.json())
      .then(data => {
        const nodes = data.results;
        this.setState({nodes})
      })
  }

  render(){
    return (
      <ul>
        {this.state.nodes.map(node => <li key={node.name.first} >{node.name.first}</li>)}
      </ul>
    )
  }
}

Worked example here. Hope it makes sense.

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

Comments

0
import React from 'react';
import ReactDOM from 'react-dom';

class Users extends React.Component{
  constructor(props) {
     super(props)
     this.state = {
       nodes: []
     }
     this.load()
  }

  load() {
    const url = 'https://randomuser.me/api/?results=5';
    return fetch(url)
    .then(response => response.json())
    .then(({results:nodes}) => this.setState({nodes}))
   }

   render() {
     let {nodes} = this.state
     return <ul>{nodes.map(({name:{first}}) => <li>{first}</li>)}</ul>
   }
 }

 ReactDOM.render(
     <Users />,
     document.getElementById('main')
 );

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.