What is data fetching?
Data fetching is a concept that allows data from APIs or databases to be transferred into your code. This allows a large amount of dynamic data to be transferred and used in your code.
Writing Code - Setup
For the setup, you are going to create a next app and if you are unsure of how to do that, you can have a look at my blog which dives deep into creating nextjs apps and the basics
After completing that we are going to clean up some of the code. Inside the page located at the root folder, delete everything and add a div with some text inside it.
export default page() {
return (
<div>
HelloWorld
</div>
)
}
The next thing to clear up is the gloabal.css page. Delete everything inside except for the tailwindcss imports if you have imported them into your application.
That is everything for the clean-up section.
Writing Code - Using an API
Now that you have completed the setup, we can move on.
In this blog, we will be fetching an API called the Dog API. This API fetches dog pictures and displays them on their page. We will be fetching this API and will be grabbing the picture URL in JSON format. This API formats its pictures in JSON format, so we can take in these properties, message and status. By doing so we can display the different pictures that the API gives us.
The first step in fetching the API is going back to our code and starting the application in localhost.
Now that the application is up and running we can start fetching this API
Writing Code - API Code
The first step in fetching the API is to create a new function on your page called getDogs.
async function getDogs() {}
Make sure this function is async as we will be awaiting data from the website. Then you are going to create a const called response. This variable is responsible for collecting the data.
const reponse = await fetch('https://dog.ceo/api/breeds/image/random')
The response is awaiting a fetch call that is directed to the website URL. In this case, it is 'dog.ceo/api/breeds/image/random'. You can get this URL by going to the website and copying it from the front page.
Then we are going to create another const called data.
const reponse = await fetch('https://dog.ceo/api/breeds/image/random')
const data = await reponse.json()
This data is responsible for collecting the request from the response fetch and converting it into JSON format.
const reponse = await fetch('https://dog.ceo/api/breeds/image/random')
const data = await reponse.json()
return data
Then we are going to return data
Now inside the page function, we will create a variable called dogs to call the getDogs function.
const dogs = await getDogs()
Just to test it out, we will console log dogs to see the result.
const dogs = await getDogs()
console.log(dogs)
If you see the terminal inside of VisualStudioCode, you will see a message and status.
Now that it is working we can use it in our application.
<Image src={dogs.message} className="w-fit h-fit" alt="dogs" width="200" height="200"/>
We can do this by adding an Image from the nextjs library components and the src will be dogs.message since that is where the URL is held. Making sure we have a width and height as well as an alt, we can have a look at our application.
But you will notice a message error. This is because we are using an external source and nextjs is telling us that we don't trust it and that we have to list it in our library.
We can do this by going into the next-config.js.
Inside here we are going to add inside of the curly braces an images tag and inside that, a domain tag that lists the domain name.
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
domains: ['images.dog.ceo'],
}
}
module.exports = nextConfig
Now if we restart the application, we can see that the application is working.
But yet again we run into a problem. When we refresh the page, the image doesn't change. This is because Next instantly cashes it into its database and keeps it there to store so every time we refresh it gives the same image over and over again.
To fix this we have to go to the fetch method and after the speech marks add a comma and put curly braces. Now inside these curly braces write cache: 'no-cashe'.
, {cache: 'no-cache',}
Now that we have fixed all the issues your application should be seeing your application change images every time you refresh your page.
Conclusion - Summary
In conclusion, you should have learned how to use API data and understand the basic concept of data fetching, JSON reading and cashing. This should allow you to use databases, API's and JSON files with the right knowledge.