#Data fetching
1 messages · Page 1 of 1 (latest)
There are several ways to update data on the client-side in Next.js. The method you choose depends on your application's specific needs. Here are a few options:
- Client-side data fetching: This is useful when your page doesn't require SEO indexing, when you don't need to pre-render your data, or when the content of your pages needs to update frequently. You can use client-side data fetching at the component level. If done at the page level, the data is fetched at runtime, and the content of the page is updated as the data changes. When used at the component level, the data is fetched at the time of the component mount, and the content of the component is updated as the data changes. Here's an example of how you can fetch data on the client side using the
useEffecthook:
import { useState, useEffect } from 'react'
function Profile() {
const [data, setData] = useState(null)
const [isLoading, setLoading] = useState(true)
useEffect(() => {
fetch('/api/profile-data')
.then((res) => res.json())
.then((data) => {
setData(data)
setLoading(false)
})
}, [])
if (isLoading) return <p>Loading...</p>
if (!data) return <p>No profile data</p>
return (
<div>
<h1>{data.name}</h1>
<p>{data.bio}</p>
</div>
)
}
Source (https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side)
- Data Fetching with Libraries: You can also use popular React libraries in the community (such as SWR (https://swr.vercel.app/) or React Query (https://tanstack.com/query/latest)) for client fetching. Here's an example of how you can use SWR to fetch data on the client side:
'use client'
import useSWR from 'swr'
const fetcher = (url: string) => fetch(url).then((r) => r.json())
export default function Page() {
const { data, error } = useSWR(
`<https://jsonplaceholder.typicode.com/posts/1`,>
fetcher
)
if (error) return 'Failed to load'
if (!data) return 'Loading...'
return data.title
}
Source (https://nextjs.org/docs/app/building-your-application/deploying/static-exports#client-components)