Reputation: 8635
this tutorial allows me to fetch data from a page. How can a component fetch data instead?
I have the component that I want to fetch data from. How can I do this?
https://nextjs.org/docs/basic-features/data-fetching#server-side-rendering
Upvotes: 6
Views: 9561
Reputation: 601
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
Upvotes: 2
Reputation: 54
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.
Upvotes: 1
Reputation: 2523
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
}, [])
}
Upvotes: 2