Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
34
rated 0 times [  37] [ 3]  / answers: 1 / hits: 9992  / 4 Years ago, wed, december 2, 2020, 12:00:00

I am under the impression that you can import api request handlers and call them directly inside of your getStaticProps function because of the documentation where it says:



Note: You should not use fetch() to call an API route in your application. Instead, directly import the API route and call its function yourself. You may need to slightly refactor your code for this approach.



I have an api route at /api/user/[id].js and the implementation looks something like this:


export default function user(req, res) {
const userId = req.query.id;
const user = getUserById(userId);
res.json(user);
}

If I want to use this handler in the getStaticProps of another page in the front-end such as /admin/user/[id].js how would I pass the id query to the request handler? Calling it without any parameters doesn't work and throws an error saying that req.query.id is undefined.


import userHandler from "../../api/user/[id].js";

export async getStaticProps(){
// This is where the api handler is getting called
const user = await userHandler();
return { props: { user } }
}


More From » node.js

 Answers
2

Here is what I would suggest to do in order to make stuff work:



  1. you do not need "dynamic" name for the file with your api calls handlers (instead of /api/user/[id].js you can create /api/user.js);

  2. you need specify a page (file) for user details view. It should be created in /pages/user/[id].js and paste getStaticProps function there. Now once you change url in browser to http://localhost:3000/user/whatever getStaticProps will be called with ({ params: {id: 'whatever'}})


getStaticProps - gets context argument which consists of several properties. All the dynamic URL parts will be stored under params property, taking into account above part this should work:


export async getStaticProps({ params }){
const user = await user(params.id);
return { props: { user } }
}

If you need some additional explanation you are welcome to ask


[#2186] Saturday, November 28, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
isham

Total Points: 69
Total Questions: 86
Total Answers: 86

Location: Anguilla
Member since Sun, Jan 29, 2023
1 Year ago
isham questions
Wed, Jan 19, 22, 00:00, 2 Years ago
Sun, Dec 1, 19, 00:00, 5 Years ago
Tue, Nov 26, 19, 00:00, 5 Years ago
;