Load Data from Contentful in React

Khaled Garbaya
InstructorKhaled Garbaya

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 2 years ago

In this lesson, you will learn how to create a react app and fetch and render some data stored in Contentful content infrastructure

Instructor: [00:00] First, we need to create a React app and seed it to the directory. After that, we need to add the Contentful SDK to our project. Let's start the server. You can see here our React app. Let's edit the app.js to make it load some content from Contentful.

[00:39] First thing, we need to delete all of these. Let's import the create client method from the SDK. Here, we initialize the client and the constructor. We will be loading some lessons data from Contentful and the client gets initialized here.

[01:05] For that, we need two pieces of data from Contentful. One is the access token, and the second is the space. To get that, we need to go to Contentful, settings, API keys, and then we click on the first item here.

[01:24] We can get the space ID from here. We paste it, and we get our delivery access token, which is a read-only access token. We save there.

[01:38] Now, in the componentDidMount, we can call the Contentful SDK and get some data. In here, we can do this, start client, and we get all the entries with the content type lesson because here, if you go to the content, this is based on the content type lesson.

[02:07] This is a [inaudible] spaced SDK. Here, we can call them and we can get response. We can set state here from response.items. Now, let's render the data. We can simply create a UL item, and here we map through the lessons in the state and display them.

[02:43] We can use the entity ID or the lesson ID as the key in here. We want to display the title from the lesson, which is in here. This is the title. To do that, we can access it through the fields object. If we save here, we can see here we are listing all the four lessons that I just created. This was one of them.

[03:19] That's how you load data in the React app from Contentful.