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}
}