简体   繁体   中英

Fetching data when specific tabs is selected - React.js

Let's say I have two tabs "Car" and a "Bus" and also a boolean "isItCar" which defaults to true.

const [isItCar, setIsItCar] = useState(true)

We do need that boolean as it's part of our API (api/isItCar when true returns cars, when false returns buses)

They have the same data, apart from the category, and they also share a layout.

Now, I wonder, what is the best way to deal with this? Should I make two API calls, or pass the boolean as api/{isItCar}? Is it even possible to do so? I would like to avoid duplicating code.

What should my tabs onselected method look like?

For example:

 <Tabs defaultActiveKey="cars" onSelect={ToggleCars}>
        <Tab eventKey="cars" title="Cars">
            <CardGroup>
                <CarList />
            </CardGroup>
        </Tab>
        <Tab eventKey="buses" title="Buses" >
            <CardGroup>
                   <CarList />
            </CardGroup>
        </Tab>
    </Tabs>

And the ToggleCars method looks like this:

   const ToggleCars = (isItCar) => {
    setIsItCar(!isItCar);
    console.log("car bool: ", isItCar);
}

Now, whenever I click on the 'Bus' tabs the console actually outputs correct bool but when I try to call data if isItCar equals to false nothing happens.

Any advice on what should I do or in which direction should I go?

If the tabs were toggle key then boolean would be the best option but passing two API calls is better. It's because a tab tag isn't chosen by boolean logic.

Let's say a user clicked Bus tag. Then the state will be changed from true to false and vice versa.

But when a user clicked Car tag from Car tag. Then the state isItCar will be changed from true to false though the Car tag is chosen still and vice versa.

So the state should be used as string . When a user clicks either tag, the state should set to the tag's name like 'cars' or 'buses'. The code would be like below,

const [isItCar, setIsItCar] = useState('cars')

   const ToggleCars = (isItCar) => {
    //The eventKey value from each tag should pass the state
    setIsItCar(event.value.eventKey);
    console.log("car bool: ", isItCar);
}

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