Retrieve information by utilizing query string parameters in Next.js

When using my getInitialProps function, I make two requests to fetch data.

Now, I want to add a condition to make an additional request if the query params key is for a legal person. For example, if the URL is

https://www.example.com.br/?legal-person
, I need to fetch data from one URL, otherwise from another URL.

I noticed that Next.js provides the query object which contains this information. I attempted to use an if statement but encountered an error:

This condition will always return 'false' since the types 'ParsedUrlQuery' and 'string' have no overlap.

However, I am unsure if my approach was correct or if there is a better way to handle this situation.

CompareLoans.getInitialProps = async ({query}) => {

  const loanTypesRes = await fetch(`${process.env.BFF_API}/api/loan-types/`)
  const loanTypesResJson = await loanTypesRes.json()

  if (query === 'legal-person') {
   const initialLoans = await fetch(`${process.env.BFF_API}/api/loans-legal-person/initial`)
   const initialLoansJson = await initialLoans.json()

  } else {
   const initialLoans = await fetch(`${process.env.BFF_API}/api/loans/initial`)
   const initialLoansJson = await initialLoans.json()
  }
  
  return {loanTypes: loanTypesResJson, initialLoans: initialLoansJson}

}

Answer №1

The error message indicates that the variable query is an instance of the ParsedUrlQuery object and not a simple string like 'legal-person'.

To resolve this issue, you should verify if the key legal-person exists within the query object instead.

CompareLoans.getInitialProps = async ({ query }) => {
    // Add your custom logic here

    if (Object.keys(query).includes('legal-person')) {
        // Execute code when `legal-person` is found in the query
    } else {
        // Execute alternate code
    }

    // Add more custom logic here
}

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

Is there an alternative method to retrieve the client's user agent if getStaticProps and getServerSideProps cannot be used together?

I am currently facing a challenge with the website I'm working on as it lacks a responsive design. This means that the view I display is dependent on the user agent of the client. In order to achieve this, I have been using getServerSideProps to deter ...

Give properties to a function that is being spread inside an object

While working with React, I am facing a challenge of passing props from the instanced component into the mockFn function. The code example below is extracted and incorporates Material UI, but I am struggling on how to structure it in order to have access t ...

Express.js Res redirection problem occurring with Backbone.js due to failure in redirecting hashtag URLs

Issue Summary: Having trouble with Express.js redirect functionality. The problem occurs when trying to redirect after entering /#impulse, but works fine with /impulse/. Server processes the request for /#impulse before applying redirect checks, which re ...

What are the steps to enable ajax communication with a database for posting, retrieving, and removing data?

Is there a way to utilize ajax for posting, deleting, and getting data from a database? I am looking to post content and then be able to delete it through the following link: (this is part of an assignment) However, I must use /ajax/addrecord.php and /a ...

Trouble with jQuery event.keyCode in detecting alphanumeric characters

I recently developed a script that is supposed to detect the key the user clicks and perform an action based on whether it is alphanumeric. However, I am encountering an issue as the script does not seem to be working as expected, and I am not receiving an ...

Tips for creating a dynamic sidebar animation

I have recently delved into the world of web design and am eager to incorporate a sidebar into my project. While browsing through w3school, I came across a design that caught my eye, but I found myself struggling to grasp certain concepts like the 'a& ...

What steps can be taken to hide empty items in a list from being shown?

When I map over an array of books to display the titles in a list, I encounter an issue with the initial empty string value for the title. This causes the list to render an empty item initially. Below is my book array: @observable books = [ {title:" ...

The Bootstrap tooltip effectively fades away after displaying text, but it is not positioned correctly above the icon

Having some issues with my tooltip functionality. It seems to display the text on the left side and fades away upon mouseover, but it doesn't show up in a proper tooltip box over the icon as expected. I suspect that there might be a conflict between j ...

The useEffect hook in ReactJs is triggering multiple times

Encountering challenges while developing an Infinite scroll using ReactJs and Intersection observer API. Upon initial application load, the API gets called twice instead of once. This behavior may be due to strict mode, although not confirmed. Additionall ...

Guide on dynamically importing a module in Next.js from the current file

I am facing a challenge where I have multiple modules of styled components in a file that I need to import dynamically into another file. I recently discovered the method for importing a module, which requires the following code: const Heading = dynamic( ...

Tips for implementing a unique design within a nested component using NextJS App Router

https://i.stack.imgur.com/EaYOG.png Here is the structure of my app router: The root layout must be shared with everyone. However, within the login component, there is another layout.jsx that should not share the root layout but override it and use the l ...

What is the best way to retrieve information in Next.js when there are changes made to the data, whether it be new

Could you share a solution for fetching data in Next.js when data is added, deleted, or edited? I tried using useEffect with state to trigger the function but it only works when data is added. It doesn't work for edit or delete operations. I have mult ...

Browserify is unable to locate the 'jquery' module

While attempting to package my app with browserify, I encountered the following error message: Cannot find module 'jquery' from '/home/test/node_modules/backbone' I have searched for solutions to this issue, but none of them seem to ...

Retrieving the input value from embedded cells in a specific row of a table

I need the function to calculate the result of the following expression using values from the table below: a+b*c-(e/f) This calculation should exclude rows with e and f. Although I encountered a similar issue before, there was no solution for this spe ...

Enhance the appearance of TreeGrid nodes by customizing the icons according to the data within

Currently, I am working with the MUI DataGridPro component and my goal is to customize the icons of the TreeGrid nodes based on the data. This image illustrates what I hope to achieve: https://i.stack.imgur.com/nMxy9.png Despite consulting the official do ...

Creating a Copy of an Object in JavaScript that Automatically Updates When the Original is Changed

I am in the process of developing a planner/calendar website with a repeat feature. var chain = _.chain(state.items).filter({'id': 1}).head().value(); console.log(chain); After filtering one object, I am wondering how to create a duplicate of c ...

Dynamic Field Validation in Angular 6: Ensuring Data Integrity for Dynamic Input Fields

After successfully implementing validation for one field in my reactive form, I encountered an issue with validating dynamically added input fields. My goal is to make both input fields required for every row. The challenge seems to be accessing the forma ...

Improving code efficiency for checkboxes in upcoming TypeScript versions

Is it possible to create a single checkbox component and dynamically pass different values to it without repeating code? I have set up these checkboxes to help me check the maximum and minimum values of some API data. const[checkValMax, setCheckValMax]= u ...

Organizing your Next.js folders to seamlessly redirect to a thank you page after successfully hitting an API from various pages

Recently, I started working with Next.js and have successfully created multiple pages such as pageA, pageB, pageC, as well as a folder containing pageX, pageY, and pageZ within the pages directory. Each of these pages features a form where, upon receiving ...

Automatically selecting a row within Material-UI's data grid using React code

Currently, I am in the process of developing a React web application and utilizing DataGrid from Material-UI by Google. The grid displays based on the user's selection from a select list (e.g., if the select list consists of fruits and the user choose ...