简体   繁体   中英

Call rest api endpoint when tab is active

I am using Tabs to switch content on my website. Each Tab has different content loaded from rest API.

Is there any way how to call REST API endpoint only when a Tab is active and not when the component mounts (What I saw in console is that each tab calls API at the same time)? Also I would like to call API only once per each Tab.

Thanks in advance.

You should avoid mounting the tabs all at once, but only the current tab that is visible. The Material-UI sample code is not really ideal for you use-case.
In your case, there should be a state control in the parent component that is rendering the tab where you can select which tab is mounted at a given point in time.
One way to deal with it would be via URL query string/parameters. Put a URL parameter to control which tab should be mounted and let the parent component handle this.
That way, only the current active tab will be mounted, thus calling your REST API.
That also has an extra benefit which is you can bookmark the URL or share it and the user will land on the right tab when the component is mounted.

Needed same functionality for my app I was able to do it with selectedTabValue and index of the tab panel.

<Paper variant="outlined">
            <Paper square sx={{ backgroundColor: "rgba(0, 0, 0, .03)" }}>
              <Tabs
                value={selectedTabValue}
                onChange={handleTabChange}
                indicatorColor="primary"
                textColor="primary"
                variant="standard"
                aria-label="pr-category-tabs"
              >
                <Tab label={"My PRs"} {...a11yProps(0)} />
                <Tab label={"Open PRs"} {...a11yProps(1)}  />
                <Tab label={"Merged PRs"} {...a11yProps(2)}  />
                <Tab label={"Weekly PRs"} {...a11yProps(3)}  />
              </Tabs>
            </Paper>
            <Paper square>
              <TabPanel value={selectedTabValue} index={0}>
                {selectedTabValue === 0 && <ApiCallComponent url={"url0"} />}
              </TabPanel>
              <TabPanel value={selectedTabValue} index={1}>
                {selectedTabValue === 1 && <ApiCallComponent url={"urll1"} />}
              </TabPanel>
              <TabPanel value={selectedTabValue} index={2}>
                {selectedTabValue === 2 && <ApiCallComponent url={"url2"} />}
              </TabPanel>
              <TabPanel value={selectedTabValue} index={3}>
                {selectedTabValue === 3 && <ApiCallComponent url={"url3"} />}
              </TabPanel>
            </Paper>
          </Paper>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM