Home > Mobile >  Routing to page A or Page B based on API response
Routing to page A or Page B based on API response

Time:11-11

I am stuck on an issue. Let's say I have a home page. From this home page, I want to route to either page A or page B.

I have a list of items on the home page and what I need to do is when I click on any item in the list, it makes a GET API call, and based on one field in the response which is a boolean, I either need to redirect to page A or page B.

Basically, I need to call an API on the click of the item and get the response before it is routed to either Page A or Page B.

Many thanks in advance

CodePudding user response:

if you're using Next.JS, use useRouter prop to achieve this.

for example

import {useRouter} from "next/router";

export default function Page() {
    const router = useRouter()

    async function route() {
        let res = await apiFunctionCall();
        if (res) {
            await router.replace({
                pathname: '/page1'
            })
        } else {
            await router.replace({
                pathname: 'page2'
            })
        }
    }
}

CodePudding user response:

The closest solution I could get is to create a Lazy loaded component which calls the API and then based on the response, routes to either page A or Page B.

Before routing to the correct page based on the data that has been returned, the data first needs to be stored in a variable. The data will be stored in the res variable. The if else statement will then route to either page A or B based on the data.

<code>const Response = res.data;

if(Response.type === 'A'){
  this.props.history.push('/page-a');
} else {
  this.props.history.push('/page-b');
}
</code>
  • Related