Skip to content
Advertisement

Show fetch results in render return() in React.js

My question is about how to show array results in render return().
I made a fetch to the API and now I get results that get stored in a array. I need to show this results but I tried with a for{} inside the return and it doesn’t work, and I also tried with .map and the map is undefined.

fetch(url + '/couch-model/?limit=10&offset=0', {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Authorization': 'JWT ' + (JSON.parse(localStorage.getItem('token')).token)
        }
    }).then(res => {
        if (res.ok) {
            return res.json();
        } else {
            throw Error(res.statusText);
        }
    }).then(json => {
        this.setState({
             models: json.results
        }, () => {
            /*console.log('modelosJSON: ', json);*/
        });
    })

render() {
    const { isLoaded } = this.state;
    const modelsArray = this.state.models;

    console.log('modelos: ', modelsArray);

    if (!isLoaded) {
        return (
            <div>Loading...</div>
        )
    } else {

        return (
            <div>
                /*show results here*/
            </div>
        )
   }
}

The array is this: modelsArray in console

Advertisement

Answer

The array of models is the results of the json returned from your fetch, so you can set that as models in your state instead, and set isLoaded to true so the loading indicator is hidden when the models are loaded.

Example

class App extends React.Component {
  state = { isLoaded: false, models: [] };

  componentDidMount() {
    fetch(url + "/couch-model/?limit=10&offset=0", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
        Authorization: "JWT " + JSON.parse(localStorage.getItem("token")).token
      }
    })
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw Error(res.statusText);
        }
      })
      .then(json => {
        this.setState({
          models: json.results,
          isLoaded: true
        });
      });
  }

  render() {
    const { isLoaded, models } = this.state;

    if (!isLoaded) {
      return <div>Loading...</div>;
    }

    return <div>{models.map(model => <div key={model.id}>{model.code}</div>)}</div>;
  }
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement