#Data fetching

1 messages · Page 1 of 1 (latest)

silk zephyrBOT
#

Hi @pure ledge. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

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:

  1. 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 useEffect hook:
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)

  1. 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)

Remember, using client-side data fetching can affect the performance of your application and the load speed of your pages. This is because the data fetching is done at the time of the component or pages mount, and the data is not cached. Therefore, it's important to consider these factors when deciding on a data fetching strategy.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: