user2128
user2128

Reputation: 640

Call Rest API based on the tab selected using react

I have list of Rest APIs which needs to be called one after the other to get the final data. Once the final data is fetched, I display the data in the grid. I also have two tabs where I display different set of data. The difference occurs in the last step of chain of APIs fetched. Currently, I fetch both sets of data and keep it ready and pass it when the respective tab is selected. But to make the code efficient, I would like to fetch the API when its respective tab is selected.

const getApiResources = async() => {

//chain of APIs
const lastStepA = fetch("/TabAdata");
const lastStepB = fetch("/TabBdata");

}

<TabGroup 
        activeIndex = {selectedTab}
        onActiveIndexChange={(valueIndex) => {setTab(valueIndex)}}
                            variant="primary">
             <Tab label='Tab A'>
                            <div>
                             <Grid data="tabAdata"/>
                            </div>
             </Tab>
            <Tab label='Tab B'>
            <div>
               <Grid data="tabBdata"/>

            </div>
            </Tab>
</TabGroup>

I would like to introduce if-else stating that if particular tab is selected then fetch API A or else fetch API B. How do I capture the tab selected ? Is that an efficient way of handling the tabs ?

Upvotes: 0

Views: 1319

Answers (1)

vadersfather
vadersfather

Reputation: 9289

You can observe changes to your selectedTab state using the useEffect hook

import { useState, useEffect } from 'react'

const MyComponent = () => {
  const [selectedTab, setTab] = useState(0)

  useEffect(() => {
     let response

     if (selectedTab === 0) {
       response = await fetchTab0()
     } else if (selectedTab === 1) {
       response = await fetchTab1()
     } // selectedTab === 2, etc.
  }, [selectedTab]) // populate the dependency list with state/props to observe

  return (
    <TabGroup activeIndex={selectedTab} onActiveIndexChange={setTab}>
      ...
    </TabGroup>
  )
}

Upvotes: 1

Related Questions