What is the best way to retrieve a query in Next.js?

I am facing an issue with two components in Next.js. Let's call them <Navbar /> and <SearchResult />.

The <Navbar /> includes a search bar where users can search for items, and a Search button. When the user clicks on the Search button, they are supposed to be redirected to the <SearchResult /> page where the results should be displayed. I am able to send the searched query from the <Navbar /> component but I am struggling to capture it in the <SearchResult /> component.

//Even though I can see the query in the URL bar (

localhost:3000/searchresult?query=somequery
), when I try to log it in the console, it shows undefined.

Below is the code snippet for my <Navbar />:

'use client'
import { useRouter } from "next/navigation";
import { useState } from "react";

const NavBar = () => {

    const router = useRouter()


    const [searchQuery, setSearchQuery] = useState('')

    const handleSearch = async (e: React.FormEvent) => {
      e.preventDefault()
      
        setSearchQuery(searchQuery)

        //redirect the user to searchresults page
        router.push(`/searchresults?query=${searchQuery}`)
      }

      return (<Navbar className="bg-transparent">
          <NavbarItem className="bg-white rounded-md" >
            <input 
              type="text" 
              className="outline-none text-black p-2 text-small rounded-l-md"
              placeholder="Search for a Character"
              value={searchQuery}
              onChange={(e)=> setSearchQuery(e.target.value)}/>
            <button 
              className="text-black px-2 hover:text-emerald-400 transition-colors"
              type="submit"
              onClick={handleSearch}>Search</button>
          </NavbarItem>
        </NavbarContent>
      </Navbar>)
}

export default NavBar

And this is the code for my <SearchResult /> component:

'use client'

import { useRouter } from "next/navigation"

const page = ({params} : {params: any}) => {
  const router = useRouter()

  const { searchQuery } = useParams()

  console.log(searchQuery)

    return (
      <div>
         Hello..
      </div>
    )
  }

export default page

I have tried various solutions but haven't been able to resolve this issue. Any assistance would be greatly appreciated!

Answer №1

It appears that the function you are seeking is called useSearchParams.

'use client'
 
import { useSearchParams } from 'next/navigation'
 
export default function SearchBar() {
  const searchParams = useSearchParams()
 
  const query = searchParams.get('query')
 
  // URL -> `/dashboard?query=my-project`
  // `query` -> 'my-project'
  return <>The query: {query}</>
}

For more information, visit: https://nextjs.org/docs/app/api-reference/functions/use-search-params

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message encountered: Missing property status in TypeScript code

An error occurs in the refetchInterval when accessing data.status, with a message saying "property status does not exist" chatwrapper.tsx const ChatWrapper = ({ fileId }: ChatWrapperProps) => { const { data, isLoading } = trpc.getFileUploadStatus.use ...

Why are my images not displaying in Next.js when using Laravel API, even though the paths and configurations are correct? What could be the reason behind

I am currently working on a project that combines Next.js with a Laravel API. One of the functionalities of the project allows users to upload the title, description, and image to the database. Once uploaded, the images are stored in the storage/app/produ ...

Encountering this issue in the _document.js file within Next.js

I'm facing an error with my Next.js project while trying to integrate Material-UI. I followed a tutorial and implemented the _document.js code, but the issue persists despite spending hours troubleshooting. Here's a link to the screenshot of the ...

Leveraging react-query with next-mdx-remote MDX Components?

I have been using next-mdx-remote in my next.js project. One of the components I've passed to it makes API calls using axios, which has been working well. However, I now want to switch to using react-query. When implementing this change, I encountered ...

What could be causing getStaticProps to receive an incorrect slug value?

Currently, I am encountering an issue with obtaining the correct slug in getStaticProps(). My goal is to retrieve the translated slug for a specific page (for example: the about page). The getStaticPaths() function is able to generate the correct object. ...

router.query is returning an empty object when using Next.js

Here is how my folders are organized: https://i.stack.imgur.com/TfBtv.png In addition, here is a snippet of my code: const router = useRouter(); const { id } = router.query; The issue I'm facing is that the id is returning {} instead of the actual ...

Tips for fixing the Next.js installation error with yarn: Ensure that options.env['npm_config__p_a_c_k_a_g_e___l_o_c_k_'] is a string that does not contain null bytes

When attempting to create a Next.js app with yarn using "yarn create next-app", an error is thrown stating: An unexpected error occurred: "The property 'options.env['npm_config__p_a_c_k_a_g_e___l_o_c_k_']' must be a string without null ...

The Google APIs sheet API is throwing an error message stating "Invalid grant: account not found"

I need to retrieve data from a spreadsheet using the Sheet API. After setting up a project in Google Cloud Platform and creating a service account, I granted the account permission to edit the spreadsheet. I then downloaded the credentials in JSON format. ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

Experiencing trouble with cross-origin resource sharing when attempting to transfer data to my server

"Access to XMLHttpRequest at 'http://localhost:3000/campgrounds/6411f03e718f68104cac045a' (redirected from 'http://localhost:5000/campgrounds') from origin 'http://localhost:3000' has been blocked by CORS policy: Response ...

I am facing an issue where the state in Next.js React does not get updated when passing a

"use client"; import { EntityType, World } from "@/types/World"; import React, { useState } from "react"; import dynamic from "next/dynamic"; ; let RayTracingPage = dynamic(()=>import("./RayTracingCanvas&qu ...

Using conditional CSS in React/Next.js

While using Next.js, I have implemented conditional rendering on components successfully. However, I am facing an issue where the CSS styles differ between different components. Code 1: import React from "react"; import Profile from "../../ ...

The information retrieved from Firebase through the use of useSWR is coming back as null

During my course, I am utilizing useSWR to fetch data from Firebase and then using it to update the state. However, when I attempt to log the data in the console, it shows up as undefined and the screen displays a loading message. This is happening even ...

Utilizing two imports within the map() method

I have been considering the idea of incorporating two imports within map() in my React code. This is how my code looks: {this.state.dataExample.map(item => ( <ItemsSection nameSection={item.name} /> item.dat ...

Maintaining Aspect Ratio and Adding Letterboxes with Next.js Image

In my Next.js app, there is a section dedicated to displaying selected photos from a gallery. It's crucial for this area to maintain a fixed size of 566px*425px as users navigate through images or when a photo is loading. While the layout is responsiv ...

Transform the code provided by bundleMDX into an HTML string specifically for RSS, all the while utilizing the mdx-bundler

I am currently working on developing an RSS reader and I need to convert the code returned by bundleMDX into a string. This is necessary so that I can utilize it with ReactDOMServer.renderToStaticMarkup(mdx) in my project. You can find a similar implement ...

Implementing cross-file method calls in Node.js using separate route files

//index.js file const express = require('express'); const app = express(); const PORT = 8888; const bodyParser = require('body-parser'); const userRoutes = require("./routes/user"); const adminRoutes = require("./routes/admin"); const ...

Is there a way to manage or turn off the swipe snapshot feature utilized in IOS for navigating (using JS)?

I've been assigned the challenge of fixing a troublesome bug in my next.js application. The issue arises when navigating on IOS using touch gestures, causing the page content to flicker. It appears that the browser captures a snapshot of the heap and ...

Issue in Next.js 13: Byte index exceeds limits when running 'npm run dev' command

When attempting to install Next.js 13.4.12, I utilized the command npx <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385b4a5d594c5d15565d404c1559484878090b160c1609">[email protected]</a>. The installation process ...

Strategies to manage or prevent a timezone offset while deploying a Next.js application on Vercel

Is there a way to ensure that a React/Next.js App always displays the local time in CEST, regardless of the user's location? For example, if I receive GMT time from the backend and want to offset it to display the CEST timezone, how can I achieve this ...