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>
)
}
}
Related videos on Youtube
Author by
hejhej123
Updated on May 25, 2022Comments
-
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 over 6 yearsThanks! 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 over 6 yearsEric, 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 over 6 yearsThank 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 over 6 yearsAdded
return
toreturn response.json()
. Should work now! -
hejhej123 over 6 yearsThis, sadly, doesn't work for me. It's giving me
Unexpected token
on thereturn
keyword. Could this be because of promise error handling? -
hejhej123 over 6 yearsI added brackets around it, to
{return response json()}
, but I'm still getting that the state is undefined... -
Rita Kondratyeva over 6 yearsCould you check my last answer and let me know what is in your console?
-
hejhej123 over 6 yearsHey. 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 over 6 yearsYes, 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 over 6 yearsOh. Thank you!!
-
Henry Woody about 5 yearsHello 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 sincejson
is not a string.