Load data from an external API using React

Khaled Garbaya
InstructorKhaled Garbaya
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 3 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.

egghead
egghead
~ 2 hours ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today