Refreshing Data in NextJs as Search Parameters Change

I'm currently working on developing an app that features a search bar where users can input a name. The app then queries two different APIs to gather information about that name, displays it to the user, and saves the search along with the results to mongoDb. The search form is located in the navigation and once submitted, redirects the user to a [searchName]/page that has the following structure:

  type Props = {
  searchParams: { [q: string]: string };
};

const SearchResults = async ({ searchParams }: Props) => {
  const nationalityReq: Promise<NationalizeResponse> = getNationality(
    searchParams.q,
  );
  const genderReq: Promise<GenderizeResponse> = getGenderData(searchParams.q);

  const [nationalityData, genderData] = await Promise.all([
    nationalityReq,
    genderReq,
  ]);

  const result: SearchResult = {
    search: searchParams.q,
    results: {
      nationality: nationalityData,
      gender: genderData,
    },
  };

  await createSearchResult(result);

  return (
    <div className="flex-col space-y-14">
      HTML with results
    </div>
  );
};

I am facing an issue where the API fetching process does not run every time I change the search parameter by typing in the search bar and pressing enter. I'm unsure how to resolve this problem. Any suggestions or help would be greatly appreciated.

Answer №1

One possible reason for this issue is that the component may not be re-rendering with each search action, causing the fetch requests to not get triggered. Implementing a simple useEffect hook could potentially solve this problem.

useEffect(() => {
    // Use an async function to fetch data
    // Call the function within the useEffect hook
}, [searchParams]);

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

How can I retrieve the last query using mysql2 in a more efficient way?

In my Next.js project using mysql2, I am looking for a way to retrieve the last query executed. Below is an example of the code snippet: try { const [rows] = await db.query('SELECT * FROM stores_new WHERE store_id = ?', [store_id]); //console.lo ...

What is the process of encoding a string for HTML display using JavaScript?

Recently, I developed a webpage for creating blog posts. To handle the description input, I integrated CKEDITOR. However, when I save the data in my mongo database, it is stored as: '<p>How are you?</p>\r\n' Surprisingly, ...

`Can you provide instructions on modifying CSS using JavaScript once the window size reaches a specified threshold?`

Is there a way to use JavaScript to automatically adjust the font size when the screen reaches 1050px? ...

Effective methods for transferring parameters between two separate JavaScript files within an express.js application

Currently, I am working with Express.js and facing a challenge in passing parameters from one JavaScript file to another. How can this be accomplished? The two files involved are 1. process.js var WebPageTest = require('webpagetest'); var wpt ...

Vercel threw a FUNCTION_INVOCATION_FAILED error my way

I am not encountering any errors locally, only in production. My getServerSideProps function is very simple. What could be causing this? export const getServerSideProps: GetServerSideProps = async (ctx) => { return { props: { org ...

Access a webpage whose URL has been dynamically assigned using JavaScript

I have a website that consists of a single page and features four tabs. Whenever a tab is clicked, it displays the corresponding content in a div while hiding the other three divs along with their respective content. To ensure a smooth user experience, I u ...

What is the best way to showcase information within a node framework?

I am looking to create a family tree using the MVC framework. Furthermore, I need to be able to insert data with relationships. I have object data that I would like to display along with its entities in a node structure. Any assistance on this matter wou ...

Tips for sorting through and minimizing data based on the most recent date

info = { start: 1, data: [ { name: 'Maria', date: '2020-02-15 }, { name: 'Paula', date: '2020-06-10 }, { name: 'Eva', date: '2020-12-05 }, { name: 'Sophia', date ...

Troubleshooting error handling in Node.js using Express and MongoDB

hey there, I'm new to Node.js and I'm working on creating a basic notes app using express and MongoDB. However, I'm encountering an issue when trying to update a note which displays "Cannot PUT" followed by the note's ID. Below is the ...

What is the best way to incorporate an image zoom-in effect into a flexible-sized block?

Having a fluid grid with 3 blocks in one row, each set to width:33.3%. The images within these blocks are set to width: 100% and height: auto. I am looking to implement a zoom-in effect on hover for these images without changing the height of the blocks. I ...

Determine whether there is text present on a webpage using JavaScript

I am familiar with Python coding from selenium import webdriver driver = webdriver.Chrome() driver.get('http://WEBSITE') assert 'TEXT' in driver.page_source However, I now require the equivalent JavaScript code. ...

Mastering the art of utilizing callbacks in AngularJS for consuming an API

Having trouble handling data from an API and structuring it effectively before passing it to the controller. I've created a factory that retrieves user data from the API, but the provideAllUserData function is causing issues. Below is my services.js: ...

JavaScript code for displaying and concealing elements

I have a simple requirement where I need to check for a variable and display or hide a class based on its value. This is being done on a SharePoint publishing page. The snippet below is not working as expected: if (source === 'show') { $(&a ...

Redux does not have the capability to insert an object into an array

I'm currently learning about redux and I've encountered an issue trying to add multiple objects into the initialState array. I attempted using the push() method, but it isn't working as expected. The submitter value is being passed to my act ...

Integration of a QR code scanner on a WordPress website page

I'm in the process of setting up a QR code scanner on my Wordpress site or within a popup. The goal is for users to be able to scan a QR code when they visit the page/popup link. Specifically, the QR code will represent a WooCommerce product URL, and ...

What is the source of the compiler options in tsconfig.json?

Currently utilizing Typescript in NestJs, I have incorporated various packages. However, the specific package responsible for altering these settings remains unknown to me: "checkJs": false, "skipLibCheck": true Is there a method to ...

React hook dom and material-ui FormControlLabel are causing a checkbox input to return an empty string instead of the expected true/false value

I am currently working on displaying the values returned from a form, specifically focusing on the Checkbox section. <FormControlLabel control={<Checkbox {...register('remember')} name="remember" color="primary" defaultV ...

Trouble arises when implementing personalized buttons on the Slick JS slider

Are you struggling to customize buttons for your Slick Slider JS? I am facing a similar issue with applying my own button styles to the slider. I am interested in using arrow icons instead of the default buttons. Here is the HTML code snippet: <secti ...

Attempting to create a slider utilizing jQuery

I'm currently working on creating a slider using jquery. I have downloaded the cycle plugin for the slider and included it in my file. The slider consists of 7 pictures. Below is the code I am using, can someone please help me identify any issues? &l ...

jQuery AJAX in ASP.NET MVC

I am developing a website that displays comments on each user's page and allows other users to add comments. My goal is to have the comment form visible on the same page, so when a user adds a comment, it gets saved in the database and appears instant ...