After several days of debugging and research, I finally found a solution to the errors arising from fetching json data in next.js.
First of all, you might be aware of the initial method of doing this which is prior to Next.js 13. Some people also claimed the old method had been working for them. But if you are like me who have tried several options and still couldnt get your application running, Here is a step by step guide i have made to assist you get rid of your errors.
The old ways of doing this was to use a built in Next.js tool called getStaticProps. This is a pre-rendering sever side tool used to fetch data in real time.
Now, that was the old way of doing this which might still work for you. But after Next.js 13 was introduced, changes were made on how we could fetch JSON data, This involves the use of Async components. We can now render systems using Promises with async & await when utilizing async components.
STEP 1 - Fetching From an API
Innitialize your projecet using the default commands
npx create-next-app {project-name}
Clear out the default pages.js file in the app folder.
Create a lib folder in the root directory of your application and create two seperste files in it, a data.json file and getdata.js file.
In this first step, we will only be making use of the getdata.js file.
Create an async function that exports getData() and insert your desired link where you will like to fetch your data from.
export async function getData(){
const res = await fetch("https://jsonplaceholder.typicode.com/posts")
return res.json()
}
In the pages.js, import the getData() function
import { getLocalData } from "@/lib/getdata"
Create an async function in your home componnet and await your fetched data using a variable
export default async function Home() {
const posts = await getLocalData()
}
- Return the following code to map your fetched data with your element
return (
<div>
{posts.map((post) => {
return (
<div key={post.id}>
<p>{post.title}</p>
{/* {JSON.stringify(post)} */}
</div>
)
})}
</div>
)
You can also stringify your data which is going to display the whole fetched data in a string format on your homepaage
{JSON.stringify(post)}
Final code should look like this in the page.js
STEP 2 Fetching Locally
It's now time to make use of the data.json file.
this file is going to contain a raw object of your data.
The whole process is still the same as step 1, just that we need to fetch this data.json file in a different way using our getdata.js file
//=========== To fetch data locally
import fsPromises from 'fs/promises';
import path from 'path'
export async function getLocalData() {
// Get the path of the json file
const filePath = path.join(process.cwd(), 'lib/data.json');
// Read the json file
const jsonData = await fsPromises.readFile(filePath);
// Parse data as json
const objectData = JSON.parse(jsonData);
return objectData
}
- now we can run our development server to see our output.
npm run dev
...And now we are finally done, your json data should be displayed on your browser.
-you could make tweaks and adjustments on how you want your data to be displayed.
I will also drop the link to the repository on github below. please do ensure to follow for more... cheers!
https://github.com/FeeqCodes/solved-Next.js-fetch-issue
Top comments (1)
jnjnj