Home > Back-end >  Check if query value is empty in NextJS using path parameter
Check if query value is empty in NextJS using path parameter

Time:10-22

I'm currently looking for a way wherein I would be able to know if the query value is empty.

I'm doing it using the path parameter method. I have the file pages/search/[variable1].js

Here is my code:

import { useRouter } from "next/router"

const Variable= () => {
  const router = useRouter()
  const { variable1 } = router.query
  console.log(variable1);
}

For example, I'm accessing localhost:3000/search/abc, the console would display abc. If I access it through localhost:3000/search/, the console does not display anything. What could be the possible condition so that I can check if variable1 is empty? I tried doing ternary operator variable1? console.log("not empty") : console.log("empty") but I still don't see empty in the console.

CodePudding user response:

If you don't have page defined under pages/search/index.js but only pages/search/[variable1].js this means that your page [variable1].js will never catch /search route and will never show what you are expecting.

You have 2 options here:

  1. change your page definition to catch all routes under search, so you would change path to pages/search/[...variable1].js which would also catch search index route(/search)
  2. to simply create page under pages/search/index.js and use query params to catch search variable

CodePudding user response:

To access localhost:3000/search, you need to have index.js folder in the relevant path.

The expectation of the localhost:3000/search/[veriable1].js folder is that it expects a query after the search. So localhost:3000/search and localhost:3000/search/_example_ are not the same page and they cannot access queries through each other.

  • Related