How to call Route Handler within client component? #58896
Replies: 4 comments 4 replies
-
Hi, You have to use an effect, and state, and later on, the React team says you can use a new hook called I think the docs are assuming that you understand For the React specific case though, typically, we couple to a promise in an use-effect: useEffect(() => {
somePromise().then(/* do something when it resolves */).catch(/* do something when it rejects */)
}, [/* dependencies */]); So the most basic approach, called, Call it from a client, is referring to sending a fetch request. Then it is up to you, how to use that request/response. Do remember that it is not only your React client code that can make requests to your handler. It is available for everyone to reach. Note that this approach can quickly become overwhelming, as asynchronous work does require paying attention to a bunch of details. You might benefit from using Also, this means that you won't have the data on your first render, because on SSR, you'll just have an empty shell. If you want to have data, then refactor the component, so that you can fetch on the server, directly from its source, avoiding Router Handlers, and pass that as props to the client components. |
Beta Was this translation helpful? Give feedback.
-
I think you don't need to use 'use client' in that component and do the basic async and await fetch call it should work. |
Beta Was this translation helpful? Give feedback.
-
Thanks, valuable info |
Beta Was this translation helpful? Give feedback.
-
it helped me a lot.thanks |
Beta Was this translation helpful? Give feedback.
-
Hi, i'm developing app with latest app router and route handler patterns.
How should I fetch data from API for my component? Documentation says I can "Call Route handler from a client" https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#fetching-data-on-the-client-with-route-handlers
What does this mean?
Currently, I have:
api/route.js (my Route handler)
I can access it via
fetch('mysite.com/api...')
But how can I "call" it from client?
Component.jsx
At first, I thought calling == fetching, but I created client component And since fetch requires async, I made it async:
MyComponent.jsx
And I got error:
So, after all how should I "call route handler"? There is no examples in documentation
Beta Was this translation helpful? Give feedback.
All reactions