0

I planned to create a page with four tabs. Each tab will contain their own data. I've surfed for more than three hours how to consume API data inside Tabs. All I can see is how to create a tabs by using material UI, BootStrap, React Tabs. I am searching for a reference how to fetch API data inside tab component. All four tabs will deal with different end points. Could any one help me out that how can I handle different API calls, when I switching tabs. If I get a reference I'll try to achieve my result. Could any one help me with reference for this. Thanks in advance.

Still_Learning
  • 209
  • 3
  • 14
  • Are you using React Material UI Tabs component or you are creating a custom component? – Shivam Pathak Mar 09 '21 at 08:34
  • https://reactjs.org/docs/hooks-effect.html first try to read this then just display your data with a .map() inside a Table https://material-ui.com/components/tables/#table also consider to add a snippet of code and edit your question for have more help – BackSlashHaine Mar 09 '21 at 08:35
  • @ShivamPathak, Currently I am using Material UI. – Still_Learning Mar 09 '21 at 08:42

1 Answers1

2

Supposing that you are using MUI Tabs and you have for example 3 tabs like:

import React from 'react';
import Paper from '@material-ui/core/Paper';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';

export default function MyTabs() {
   const [value, setValue] = React.useState(0);

   const handleChange = (event, newValue) => {
     setValue(newValue);
   };

 return (
    <Paper square>
       <Tabs
         value={value}
         indicatorColor="primary"
         textColor="primary"
         onChange={handleChange}
        aria-label="disabled tabs example"
       >
          <Tab label="Tab1" />
          <Tab label="Tab2"/>
          <Tab label="Tab3" />
       </Tabs>
   </Paper>
 );
}

You could use value value to intercept the tab clicked and then call your own endpoint. So your handleChange becomes:

const handleChange = (event, newValue) => {
   switch(newValue){
       case 0:
         // call api for Tab1
         break;
       case 1:
         // call api for Tab2
         break;
       case 2:
         // call api for Tab3
         break;
       default:
         break;
   }
     setValue(newValue);
};

Note: as you can see, value starts with value 0 (const [value, setValue] = React.useState(0);) so this means that at first load you will see Tab1 and handleChange is not yet called. In this case you could use useEffect hook on tab loading in this way:

useEffect(() => {
   // call api for Tab1
},[]); //<-- this means "just one time at component loading"
Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30