Hi, I am making a simple UI with ‘JSONPLACEHOLDER’ api using react. I am fetching posts and passing it to this.posts
. But this isn’t happening.
link -https://codepen.io/fitc0de/pen/xxdQMLV
Okay several issues here.
- when you access the posts, it’s
this.state.posts
notthis.posts
- minor, because you immediately overwrite it, in the constructor,
this.posts = 0;
.posts
is an array, not a number. If the call errors, you’ll then try to runslice
on0
, which isn’t going to work. - You’re assigning directly to
this.posts
. If you are using React class components, you have to usesetState
to change the state. - The fetchData function is a weird setup where you set up a variable then assign to it inside a
then
:
Just do things one after the other, it’s much easier to see what’s going on (I’ve just dropped error handling here for the example, but probably don’tasync function fetchData() { let posts; await fetch("https://jsonplaceholder.typicode.com/posts") .then((response) => response.json()) .then((json) => (posts = json)) .catch((err) => console.log(err)); return posts; }
catch
unless you’re going to do something meaningful with it, generally just let it blow up otherwise unless you’re really sure it’s fine for it to show nothing in the app):async function fetchData() { const response = await fetch("https://jsonplaceholder.typicode.com/posts") const data = await response.json() return data; }
- make the request in the
componentDidMount
lifecycle method, rather than the constructor. So component mounts, you have an empty array of posts, then React detects that it’s mounted, runscomponentDidMount
where the data is fetched andthis.state.posts
gets populated.
Note that here is where you would handle the fetch failing: logging an error in theasync componentDidMount() { const posts = await fetchData(); this.setState({ posts }); }
fetchData
function itself is not useful.
Is it necessary to use state if you are using react. Can’t I do it without using state because I am going to set this posts
data once only.
Got it. I will remember this.
So should I code this-
async componentDidMount() {
try {
const posts = await fetchData();
this.setState({ posts });
}
catch(err){
console.log(err);
}
}
Yeah, that’s fine, though it may make more sense to put something in the UI, eg tell the user if there’s an error.
Is it necessary to use state if you are using react. Can’t I do it without using state because I am going to set this posts data once only.
That’s how React works, so yes, you need to do that.
1 Like
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.