The functionality of Router.push() seems to vary depending on the timing

I'm attempting to utilize router.push() to modify the URL when the Search button is clicked. However, I've encountered a situation where this function only works sporadically. Ideally, after clicking the button, the user should be directed to the /search page with the text input from the field, but this desired behavior isn't consistently happening and I can't identify any errors in my code.

This is the search function in my index.js:

const [searchInput, setSearchInput] = useState("");
    const router = useRouter()


    const Search = () => {
        router.push({
            pathname: "/search",
            query: {
                city: searchInput,
            }
            },
        );
    };

And here's my form in index.js:

<form className={"flex flex-col items-center mt-44 flex-grow"}>
            <h1 className={"flex justify-center font-bold pt-20 text-4xl"}>Enter address</h1>

            <div className={"flex w-full mt-5 hover:shadow-lg focus-within:shadow-lg max-w-md rounded-full border border-gray-200 px-5 py-3 items-center sm:max-w-xl lg:max-w-2xl"}>

                <input
                    value={searchInput}
                    onChange={(e) => setSearchInput(e.target.value)}
                    type={"text"} className={"flex-grow focus:outline-none"}/>
                <SearchIcon className={"h-5 text-gray-500"}/>
            </div>


            <div className={"flex flex-col w-1/2 space-y-2 justify-center mt-8 sm:space-y-0 sm:flex-row sm:space-x-4"}>
                <button
                    onClick={Search}
                    className={"btn"}>Search</button>
            </div>
        </form>

There might be something off with my WebStorm setup since the functionality seems inconsistent. I'm at a loss for what could be causing this issue.

Answer №1

It appears that the default form submission might be causing interference with your Search functionality.

A possible solution could be:

    const Search = (e) => {
        e.preventDefault();

        router.push({
            pathname: "/search",
            query: {
                city: searchInput,
            }
            },
        );
    };

For further information, refer to this link:

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

Using Swig template to evaluate a condition

I'm trying to achieve something similar using swig-template. var remId = $(this).attr('remId'); if (remId) { var end = remId.search('_'); var underscore = remId.slice(end, end + 1); var Id = remId.slice(end + 1, remId ...

Press the button within the table as its name undergoes periodic changes

I am using Python along with Selenium to automate the process of selecting and reserving a room on a website. The site displays a table containing available rooms, and my goal is to locate a specific room and click on the corresponding button within the ta ...

The proper way to retrieve data using getServerSideProps

Encountering an issue with Next.js: Upon reaching pages/users, the following error is displayed: ./node_modules/mongodb/lib/cmap/auth/gssapi.js:4:0 Module not found: Can't resolve 'dns' Import trace for requested module: ./node_modules/mon ...

Error: An attempt to make changes to a database that does not permit mutations has resulted in an InvalidStateError

I am facing an issue while attempting to initiate a transaction within the then() function. An exception is thrown when I try to do so. Below is the code snippet in question: open.onsuccess = function (e1) { var dbase = e1.target.result; $.get("https://w ...

The displayed value in the text field remains constant even when the object's attribute is modified

My issue involves the Date Text Field component of Material UI. Whenever I pass an attribute from an object, the displayed value in the Text Field does not update even when the object attribute changes. const [data, setData] = useState({ title: new Da ...

Sharing data between ejs and javascript files

When using Express, I have encountered an issue with passing a variable to an EJS file called "index.ejs". res.render("index",{passedUser:req.user.alias}) Although I am able to successfully print it using <%=passedUser%> in the EJS file, I require ...

Using the Twit package on the client side: a step-by-step guide

I have been utilizing the Twit package for searching tweets. After executing the js file in the console, I am able to see the tweets but when trying to use them on my webpage, an error 'Uncaught ReferenceError: require is not defined' pops up. Th ...

Populate Vue 3 Element-plus Virtualized Table with actual data

As a newcomer to frontend development, I am currently working on integrating Element-plus Virtualized Table with actual data. Here is the basic structure of the example: const generateColumns = (length = 10, prefix = 'column-', props?: any) => ...

Initiate an AJAX request within an existing AJAX request

On one of my pages, page A, I have a form that passes parameters to a script using AJAX. The results are loaded into div B on the same page. This setup is functioning properly. Now, I want to add another form in div B that will pass parameters to a differe ...

Why is the validate function not being executed in the Backbone Model?

I am a beginner in learning Backbone and I am attempting to implement simple validation in my Person Model. However, I am facing an issue where the validate method does not run when I set a new age. Can someone guide me on where I might be making a mistake ...

Unable to invoke the jQuery function within CakePHP3

I am having trouble calling the jQuery function mentioned below in my CakePHP3 MVC project. There are no error messages, but nothing seems to be happening. The code is set up so that jQuery gets included automatically. The function I am trying to call sh ...

Utilizing external JavaScript scripts within Next.js

For my upcoming project, I am looking to incorporate some external JavaScript files into the script. Here is an example: <script src="assets/js/productFactory.js"></script> I came across a suggestion to use Next/Head, however, this goes again ...

Automating user login with node.js and passport.js: A step-by-step guide

My login application is built using node.js and passport.js, with the session being maintained using express-session and connect-mongo. I need to ensure that users are redirected to the home page upon accessing the URL, only sending them to the login page ...

Cyrillic characters cannot be shown on vertices within Reagraph

I am currently developing a React application that involves displaying data on a graph. However, I have encountered an issue where Russian characters are not being displayed correctly on the nodes. I attempted to solve this by linking fonts using labelFont ...

"The form validation feature with regex does not seem to be functioning properly on the MUI React

I've been attempting to incorporate a regex pattern into inputProps in order to validate the Textfield and make it required, but unfortunately, neither seem to be functioning properly. Upon clicking "next," empty or incorrect inputs are still being ac ...

VUE 3 inexplicably failing to display the custom component's template, console remains error-free

I am utilizing flask, html, js for building a web application. I am currently facing an issue where the template defined in the component <add-movie> within movies.js is not being rendered into add_movies.html. The add_movies.html extends base_admin ...

Unable to view the image in browsers other than Internet Explorer

On a webpage, there is a feature where clicking on the "Add More" link should display an input box and a "Delete" button image. Surprisingly, this functionality works perfectly on IE browsers, but not on Mozilla or Chrome. In non-IE browsers, only the text ...

Using Vue.js to conditionally render content based on changes in a variable

I am facing a challenge in rendering a new element once the boolean variable waiting changes to true. The issue arises when transitioning from one v-if statement to another, as the boolean does not update until the first statement is completed. How can I s ...

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...

Leveraging PostCSS Global Data in Next.js

Utilizing PostCSS along with postcss-preset-env (now integrated into postcss-plugins monorepo) and postcss-custom-media enables the declaration of global breakpoints once, making them accessible within CSS Modules across the project. The documentation for ...