Load data from an external API using React

Khaled Garbaya
InstructorKhaled Garbaya
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

Khaled Garbaya: [0:00] Now we want to load some JSON data and render it in our Timeline component. To do that, let's first change the shape of this component, and then here we'll have few states.

[0:12] First one is the timeline, and we get setTimeline, all of these we'll get from React.useState. We will set it to an empty array.

[0:29] When this component is bound in, we need to first hit that API and get the data. We will use React.useEffect. We'll pass an empty array in here. We need to fetch this API here, and then we will get the response. We need to return the response.json. After that's done, we'll call setTimeline with the new timelineData.

[1:02] This is failing because we're not returning anything in our timeline, which we will do in a second. We need to return something here, so first let's have a div. Inside of that we'll have a header which will be Timeline. Now, we'll have a list of all the items in the timeline.

[1:26] Here we'll map through timeline. We'll have an li. To test that, first, let's display t.text. You can see here that I have my entire timeline coming from this API. Now, you get the idea. We will replace this marker to display all the content. Hit Save.

[2:01] You can see here we have a picture, we have the username and then the text.