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.
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"