Set Fetched JSON data as state and use it

12,226

Try something like this:

export default class YourComponent extends React.Component {

    constructor(props) {
        super(props);

        this.state = {data: 'false'};
    }

    componentDidMount() {
        this._getData();
    }


    _getData = () => {
        fetch("myserver.com/api/a/1")
        .then(response => {
            if (response.ok) {
                    return response;
            } else {
                let errorMessage = `${response.status(${response.statusText})`,
                error = new Error(errorMessage);
                throw(error);
            }
        })
        .then(response => response.json())
        .then(json =>{
           console.log(json);
           this.setState({ data: json.data })
        });
    }

    render() {
        return (
            <div>
               {
                this.state.data &&
                this.state.data.map( (item, key) =>
                    <div key={key}>
                        {item}
                    </div>
                )}
            </div>
        )
    }
}
Share:
12,226

Related videos on Youtube

hejhej123
Author by

hejhej123

Updated on May 25, 2022

Comments

  • hejhej123
    hejhej123 almost 2 years

    I'm a newbie to React so I'm trying to learn basic concepts.

    I'm getting data through an API I hardcoded some data into for learning purposes, with a fetch request like so:

    componentDidMount() {
        fetch("myserver.com/api/a/1")
        .then(function(response) {
            response.json()
        })
    }
    

    and in my constructor I set the state to data: 'false':

    constructor(props) {
        super(props)
    
        this.state = {data: 'false'};
    }
    

    But from here on I'm lost. I have three different strings in the JSON Object I'm getting through my API but I don't know how to access them. I've tried setting setState in componentDidMount but I'm getting loads of error.

    How do you do in situations like these? Where should I be setting state, and how do you generally access/iterate over JSON objects?

    Thanks in advance!

  • hejhej123
    hejhej123 over 6 years
    Thanks! Works well! How do I go about displaying this data in my component, ie how do I reach the array of items in the JSON object?
  • Rita Kondratyeva
    Rita Kondratyeva over 6 years
    Eric, modified my answer for simplest case. map is used for array case. {key} is for correct rerendering of item there, item - for case when you have something simple in your array, will not work if you have another array there
  • hejhej123
    hejhej123 over 6 years
    Thank you! This should work -- good explanation. Although... I'm still getting an error on .then(json => this.setState({data: json.data}));, an error of: Unhandled Rejection (TypeError): Cannot read property 'data' of undefined. Do you have any experience with this?
  • Rita Kondratyeva
    Rita Kondratyeva over 6 years
    Added return to return response.json(). Should work now!
  • hejhej123
    hejhej123 over 6 years
    This, sadly, doesn't work for me. It's giving me Unexpected token on the return keyword. Could this be because of promise error handling?
  • hejhej123
    hejhej123 over 6 years
    I added brackets around it, to {return response json()}, but I'm still getting that the state is undefined...
  • Rita Kondratyeva
    Rita Kondratyeva over 6 years
    Could you check my last answer and let me know what is in your console?
  • hejhej123
    hejhej123 over 6 years
    Hey. Thanks to you and abdul it works, using data => data instead of json => json.data. Would you care to explain the differences? I really appreciate the help!
  • Rita Kondratyeva
    Rita Kondratyeva over 6 years
    Yes, I did not know your structure clearly, so this is was only assumption about your data structure, so it would woek if your structure was for example {data:{smth: smth}}
  • hejhej123
    hejhej123 over 6 years
    Oh. Thank you!!
  • Henry Woody
    Henry Woody about 5 years
    Hello and welcome to StackOverflow! In addition to including code, it's usually best to include a short explanation of why/how your solution solves the posted problem. Also I'd suggest you check that this solution actually works because I believe JSON.parse(json) will give you a syntax error since json is not a string.