5

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

0

1 Answer 1

4

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>;
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

That worked for code, but when I access the brand's id and name {models.map(model => <div key={model.brand.id}>{model.brand.name}</div> )} returns the same position of the array. Repeats 10 times the same brand name
@SofiaRibeiro Hard to say without seeing your brand data. Don't use the brand id as key, because that might not be unique for every model. Use the model id instead, which will be unique. key={model.id}
See that image imgur.com/a/9CmvkmQ and thanks for the advice on the key @Tholle
@SofiaRibeiro model.brand.name looks correct if you want the brand name. It might be that some models are from the same brand. I don't know for sure.
I think I have to do another "for" to run the brand array
|

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.