I just want to ask how can I call an API when a user "click the search button" and display the appropriate result in NextJS. Thank you!
This is the API I'm using https://www.themealdb.com/api/json/v1/1/search.php?s=Steak and note the "Steak" word is the food I want to see.
Here is my url in development mode http://localhost:3000/search/steak/.
I want to pass the "steak" in getStaticProps and pass the result of getStaticProps in my component.
export const getStaticProps = async () => {
const res = await axios.get(
'https://www.themealdb.com/api/json/v1/1/search.php?s=Steak'
);
return {
props: {
meals: res.data,
},
};
};
I think you can't do it. GetStaticProps
render the page at build time, so you can't render a page based on user request. I suggest you to read this docs, section 'when I should use GetStaticProps' . You can use react state, or GetServerSideProps
(read the same docs). You can also static render a bunch of page using GetStaticPath
and pass, for example, the 10 most searched foods.
You can do this with getStaticPaths if you are using dynamic routes.
You can use search/[slug].js
as a dynamic route in your file based routing.
Then, in [slug].js
you would have something like:
export default function Page({ response }) {
return <div>{JSON.stringify(response)})</div>
}
// get all the possible paths for the individual ingredients
export async function getStaticPaths() {
const data = await axios.get(
'www.themealdb.com/api/json/v1/1/list.php?i=list'
);
return {
paths: data.meals.map((ingredient) => ({
params: { slug: ingredient.strIngredient.toString().toLowerCase. },
})),
fallback: false, // can also be true or 'blocking'
}
}
export async function getStaticProps({ params }) {
const { slug } = params
const response = await axios.get(
`https://www.themealdb.com/api/json/v1/1/search.php?s=${slug}`
);
return {
props: {
response
},
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.