The best way to fetch data from client components
Unanswered
Japanese Bobtail posted this in #help-forum
Japanese BobtailOP
Hi guys, please advise the best way to fetch data from client components. The thing is that now I'm using useSWR and it works strangely. I have a block of filters where I need to get data of categories and genres, useSWR throws a request only on the first API, and the second just ignores. It doesn't help even if I put the category filter and genre filter in separate components and fetch data there as well
4 Replies
Sun bear
I would create a server action like this and just call it from the client component. no need for swr or react-query.
// src/actions/data.ts
"use server"
export async function fetchData() {
// fetch logic here...
// return the information such as:
// ok: boolean
// status: number
// response: ResponseObject
// message: string
// description: string
return data
}// src/components/client-component.ts
"use client"
import { fetchData } from "@/src/actions/data"
export default function ClientComponent() {
// you can handle the loading, error & success logic by storing it in a useState
const [loading, setLoading] = useState<boolean>(false)
const [res, setRes] = useState<ResponseObject | null>(null)
const [message, setMessage] = useState<string | null>(null)
async function handleClick() {
await fetchData()
}
return (
// render the component...
<button onClick={fetchData}>Fetch Data</button>
)
}if you need to fetch the data on load useEffect will work, but you should try to avoid it and instead fetch the data in a server component higher up and pass it using the props or context to the client components
this leads to a more predictable behaviour and better performance
This is good advise as long as you remember that server actions can happen asynchronously. If you need to fetch multiple sets of data at once I would indeed use a server component to pass the data down