Reputation: 55
Hi i am having api routes which listens to incoming request ,
Code looks something like this
async function handler(req, res) {
// Run the middleware
await runMiddleware(req, res, cors)
// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
console.log(req.body)
}
export default handler
whenever this request comes in , how can i interact with this data and use these on pages?
Upvotes: 2
Views: 6039
Reputation: 427
If you need this data before the page is rendered then you would not use API routes. You can (and should) use all kinds of things directly inside getServerSideProps
OR getStaticProps
. This basically means that you could query your DB directly inside this functions. No need to go to the "server" to do that. It's a big context switch. Speaking of context, you can get url information and all sorts of things as argument to those functions mentioned above.
If you need this data after the page is rendered then you should use client-side fetch calls to get data. You can read up on that, it's basic react data fetching.
Relevant links
Context: https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#context-parameter (for accessing stuff like params, query) before the page loads
React data fetching: https://www.robinwieruch.de/react-hooks-fetch-data/
Upvotes: 1