How to Call Route Handlers from a Client Component
Answered
Erythrina gall wasp posted this in #help-forum
Erythrina gall waspOP
Hello, I'm currently using the AppRouter in Next.js and I'm trying to understand how to call Route Handlers from a Client Component. The documentation states:
From this description, it seems as if we can directly call the Route Handler similar to Server Actions, which has left me a bit confused. Or is it simply referring to using a regular fetch? I couldn't find any examples in the documentation to clarify this.
Additionally, when fetching Route Handlers from a Client Component, is it recommended to use tools like SWR or TanStack Query?
If you need to fetch data in a client component, you can call a Route Handler from the client. Route Handlers execute on the server and return the data to the client. This is useful when you don't want to expose sensitive information to the client, such as API tokens.https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-client-with-route-handlers
See the Route Handler documentation for examples.
From this description, it seems as if we can directly call the Route Handler similar to Server Actions, which has left me a bit confused. Or is it simply referring to using a regular fetch? I couldn't find any examples in the documentation to clarify this.
Additionally, when fetching Route Handlers from a Client Component, is it recommended to use tools like SWR or TanStack Query?
Answered by Clown
Also you can just
fetch() the route handler directly. You dont necessarily need React Query or SWR4 Replies
Read up on Route Handlers here:
https://nextjs.org/docs/app/building-your-application/routing/route-handlers
https://nextjs.org/docs/app/building-your-application/routing/route-handlers
Also you can just
fetch() the route handler directly. You dont necessarily need React Query or SWRAnswer
@Erythrina gall wasp is your problem solved?
Erythrina gall waspOP
Resolved! Thanks!