managing grouped buttons loading state within a map function

Viewed 31

I have two buttons accept and reject buttons, that are part of a card which is generated from a map function. I need to enable each of the cards states and set to loading independently. This is how I am currently activating the state to busy:

    const [isBusy, setBusy] = useState({});

........

setBusy(prev => ({ ...prev, [id]: true }));
        setTimeout(
            () => setBusy(prev => ({ ...prev, [id]: false })),
            3000
        );

These are the buttons

return [
            <Button loading={isBusy[id] || false} title="Invite" onPress={() => invite(id)}  />,
            <Button loading={isBusy[id] || false} title="Remove" onPress={() => reject(id)}  />,
        ];

The challenge at the moment, is clicking on Invite button activates also the state of remove button in that particular card that matches the id. This is all contained in a card displayed under a map function, each card has two buttons to be displayed, invite and reject button respectively, I need to handle the sate of these individual buttons within each card separately, so that if I click invite, isBusy is activated only for invite button and reject button is handled as separate too

1 Answers

If I understood the problem correctly, you need to have two separate states for every card and one for each button. you can change the keys to ${id}-invite and ${id}-remove or merge them into an object with id key.

const [isInviting, setInviting] = useState(true);
const [isRemoving, setRemoving] = useState(true);

then create two separate setter functions to do the job you want, and use each one in corresponding button.

Related