nextjs components fetching data

Viewed 5608
3 Answers

You can use fetch data by using useEffect. On the other hand, you can fetch data from parent component and pass data to child component.

const Component = props => {
   // You can get data from parent component.
   const parentData = props.parentData

   useEffect(() => {
     // Fetch Data here when component first mounted
   }, [])
}

For example. First create login.js page in pages folder and call api and in login.js than pass data to logincomponent.js file in component folder. It's proper way to load data in component in Next.js . Other way is use UNSAFE_componentWillMount in component to call api.

there is a new hook that NextJs provide it. this is SWR package

The team behind Next.js has created a React hook library for data fetching called SWR. It is highly recommended if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more.

sample:

import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then((res) => res.json())

function Profile() {
  const { data, error } = useSWR('/api/profile-data', fetcher)

  if (error) return <div>Failed to load</div>
  if (!data) return <div>Loading...</div>

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.bio}</p>
    </div>
  )
}

see the document:

Client-side data fetching with SWR

Related