nextjs useEffect load json data
nextjsTo load data from a JSON file in a Next.js application, you can use the useEffect hook to fetch the data in the component. Here’s an example of how you can do this:
import { useEffect, useState } from 'react'
function MyComponent() {
const [data, setData] = useState(null)
useEffect(() => {
async function loadData() {
const res = await fetch('/data.json')
const json = await res.json()
setData(json)
}
loadData()
}, [])
if (data === null) {
return <p>Loading data...</p>
}
return (
<div>
<h1>My Data</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)
}
export default MyComponent
In this example, the useEffect hook is used to fetch the data from the /data.json file when the component is mounted. The data is stored in the data state variable, and a loading message is displayed while the data is being fetched.
Once the data is loaded, it is displayed in the component. You can customize the component to display the data in any way you like.
Keep in mind that you’ll need to make sure the data.json file is available at the specified URL. You can do this by including the file in the public directory in your project, or by using a server to serve the file.
Other Article on Tag nextjs
- - fetch function mode sors, no-cors, same-origin
- - fetch request option
- - How to add Bootstrap in Next.js
- - how to minimize front in next js
- - nextjs add bootstrap
- - nextjs add Font Awesome
- - nextjs add font face in head
- - nextjs add prismjs
- - nextjs add Syntax highlighting code
- - nextjs call api