Contentful CMS with React Hooks Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Contentful is a content management system, or CMS, which is like a warehouse for all your data. In this section, we'll explore the setup part of Contentful: creating an account, adding our data model, then adding the content to Contentful. In the next section, we'll see how to make use of the Content Delivery API to fetch data and display them in our React application. First things first, we need an account. Contentful offers three different pricing plans that suits different needs. We have the community plan, the team plan, as well as their enterprise plan. Community is the free tier and offers generous features and services. We'll be using the community plan in this section. If you don't already have an account, head over to contentful.com and create one by clicking on the sign up free button at the top right corner. Then you should land on your space home. So we'll need to create our content model first, which is the structure our content should follow. Click on the content model tab, and then you'll see a add content type blue button in the middle of this screen. If you already have a few content models, the button will be located at the top right corner. So click on add content type. And we need to give our model a name. Let's name it author, so that means that we'll be creating a few authors in Contentful and fetch them in our application. The API identifier is the variable name that we'll give to this content type. Contentful automatically generates the API identifier from the name field, which is author. So let's leave it as is. You can add a description if you wish, but I will leave it as blank. And then I'll click on create. Now, you can see that I have my author content type. We will need to add some fields to our author model. So click on add field. And the first field that we'll add will be our author name. We'll also need to add a description as well as an avatar. So let's click on text for the name and the name of our field will be the name, which is the name of the author. And it will be a short text. Then click on create and configure. We'll need to check the box this fields represents the entry title, which means the name that we give to the author will be the title displayed in the content tab, that we will see later on. Next let's click on the validation tab and click on required field, which means that this field must be present for every author entry that we add to Contentful. Then let's click on confirm and it added the name field to our author model. Now let's add the description as well as the avatar. So let's click on add field. The description will be a text field as well, and it will be a long text, full text search. The name will be description, and then let's click on create and configure and under validation, we will check the required field box. Finally we'll need to add an avatar and since the avatar will be an image, let's click on media. The name of this field will be avatar. And it will be only one file. Then let's click on create and configure. Under validation, it will be a required field. Let's click on confirm. And once you're done adding the three fields, remember to click on save at the top right corner. Now our content type is done and we'll need to add a few authors to our Contentful. Let's go to unsplash.com and we'll search for avatar. If you scroll down, you will see a few images for the author avatar. Select three, download them, and then we'll go back to Contentful. Now, I have my three authors avatars downloaded from Unsplash. And I renamed each one of them to author and then a number. In Contentful, let's go to the content tab. Here we'll need to add a few entries for author. Since we only have the author as our content model, we can only add author entries in our Contentful. So let's click on add author. And you will see a form that we need to fill in. So we have a name, a description as well as an avatar. Use your imagination and fill in the forms. So for example, I will name my author, Johnny Smith. In the description, I will say, I love coding and writing about coding. Then in the avatar, we will add a media, which will be the new media. And then we'll open the file selector. And select an author to upload the image. You can rename your asset file if you wish. So I will rename it to Johnny Smith avatar. And don't forget to click on publish when you're done uploading your asset. Now close the asset tab. And when you're done filling in the form for the author, remember to click on publish. Now we'll simply do the same for the two other author avatars that we downloaded from Unsplash. Great! We added our content model as well as three different authors to Contentful. Now, we're ready to tackle the Contentful API. Before using the Contentful API, we'll need to install the package first. This package will allow us to easily fetch data from our Contentful space. If you're developing on your local machine, in the terminal, run npm install contentful. In my case, since I will be using code sandbox, I would simply add the dependency here. So I'll search for contentful and add the contentful package. If the data you'll fetch with Contentful will be shared across the entire application, it will be best to create a context and have a global state. You can learn more about the useContext and useReducer hooks in the useReducer with useContext tutorials, part one, part two and part three. In this tutorial, we'll just fetch the data with a custom hook called useContentful. To fetch data with the Content Delivery API, we need a space ID as well as a preview token. So in Contentful, click on settings and under the space setting section, click on API keys. You should see your API keys here. So if you don't already have an API key, simply click on the blue button at the top right corner called Add API key. This will create an API key for you and we'll need the space ID as well as the content preview API access token. You should also see a content delivery API access token, but for the purposes of this tutorial, we'll use the preview token instead. When working in development mode, it's best to use the . Content preview API access token, as the data fetched will include the entries in draft mode. When in production, it's best to use the Content Delivery API access token, so only the content that's published will be fetched. Then the first thing we'll need to do is to create the useContentful hook. So under the source folder, we'll create a new file and this file will be called useContentful.js. Then let's create the basic function layout, so const useContentful will be equals to a callback function. Then don't forget to export default your hook. At the top, we'll import the createClient function from Contentful. So we'll do import with curly brackets, createClient from the Contentful package. This is the function that we'll use to connect to our Contentful account. Then, inside of your hook, we'll use the create client function and this function accepts an object containing a space ID, an access token, as well as a host. Simply go back to Contentful and you need to copy your space ID, paste it for the space ID. Also copy your preview API access token, and paste it for the access token. And since we'll be using the preview token, we need to provide the host as well. In our case, we'll need to write preview.contentful.com. If you're using the delivery token, you can omit it or, instead of writing preview, you can write CDN. So we'll keep it to preview. For the purposes of this tutorial, we'll, hard-code the space and the access token. But remember to never hard-code your keys when committing to Github or pushing your work to production, because it's a big security flaw. Now that we created our client, let's save this in a client variable. Then right below this variable, we'll create a function called getAuthors. And we'll be using the getEntries function from Contentful to get all the author entries. So since the getEntries function returns a promise, we need to mark this function as asynchronous. Then let's add a try-catch statement because we want to catch any error that might be thrown from the Contentful API. In the try, we will call the client that we just created on line four dot getEntries. And this function accepts an object, which is optional. If you don't pass any argument to the function, it will fetch everything from your Contentful space. So in our case, we will specify the content type that we want to fetch, which is all the author entries. And we'll also specify the select, which means that we just want to fetch the fields and not all the system information related to each entry. If we ever run into an error, we'll console log the error, so error fetching authors and we'll print the actual error. Now, if you want to order the entries that you fetch, you can order them, for example, by fields dot name, so all the authors will be ordered by their name. And if you have another content type, for example, courses, and you wish just like only the courses with React as a subject, you can specify it by adding the fields dot subject key. And you want all the React courses like this. So in our case, we're not working with courses, we're working with authors, so we'll keep it like this. So get entries, as mentioned before, it returns a promise. So we need to add the await word in front, and let's save it in an entries variable. At the bottom, we will return entries. Then, before the closing bracket of the useContentful hook, we'll return an object, which will contain the getAuthors function. Now let's call the getAuthors function in our App.js. So at the top, in App.js, we will import useContentful from the useContentful file. Then we'll get the getAuthors function from the useContentful hook. And we'll also need to import two hooks. So at the top, we'll import useEffect, as well as you state from the React library. Now let's define both of the hooks. So, we'll define a state called authors, setAuthors, will be equals to the useState hook and by default, it will be an empty array. Right below the getAuthors, we'll define the useEffect. And we'll call to getAuthors, then, what we get in turn is a response. So for the moment we'll simply console log the response. So let's save this, refresh our page. And open the console. So you can see that we have a big object with a lot of layers and some useless data. For example, we don't need the total, we don't need the limit, we don't need the includes, we just want the items. And for each item, we want the field. If we open the avatar for each author, you can see that we also have some metadata, a sys object as well as a fields object. So we just want the fields object from the avatar, as well as the name and the description of each author. So let's go back to useContentful and we'll need to sanitize the entries object, which means that we only want to return the information that we really need. So right before the return statement, we will do const sanitizedEntries will be equals to entries dot items dot map. And for each item, we will sanitize it. So that means that we're accessing the items array, and for each item in the array, we will sanitize that object. So we'll get the avatar, which will be item dot fields dot avatar dot fields. And right below, we will return item dot fields, which means the name and the description from the author, as well as the avatar variable that we just created on line 18. And instead of returning the entries, we will be returning the sanitized entries here. So if we refresh our page, you'll see that in the console, we have an array that is being printed and for each item in the array, we have the name, the description, as well as the avatar. Great, now that we sanitized our data, we can go back to our App.js file. And instead of console logging the response, we will set authors with the response that we get from the getAuthors function. And finally, now that we have the data, we can create a new file and we'll call it AuthorCard.js. So here I will simply paste the author card that you can find in the text content below, or you can also create your own. So this author card will accept an author as a prop, and we'll show the author avatar, with their name and their description. Back in App.js, we'll simply map over the authors array, so we'll do authors dot map. So for each author and we get the index, we will display an author card. Remember to import the author card in your App.js file. Now, we need to provide a unique key for each author card. And we also need to pass the author to the author card. So let's refresh this, close the console. And you'll see your three authors in your app. We have their picture, their name as well as their description. So this was how to use the Contentful API to fetch data from your Contentful space. I hope that you learned something new in this section and don't hesitate to head over to all the other sections of this handbook to learn more about other topics on React.
Info
Channel: DesignCode
Views: 17,550
Rating: undefined out of 5
Keywords: designcode, iOS app design, course for beginners, contentful, api, content, management, system, cms, data, fetch, structure, model, delivery, sdk, react, hooks, use effect, use state, try, catch, asynchronous, promise, await
Id: AWie7zwAyU0
Channel Id: undefined
Length: 13min 15sec (795 seconds)
Published: Wed Dec 01 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.