T
TanStack3y ago
rare-sapphire

Use toggle to enable different useMutation call

I have a toggle button which gives true/false value in useState, then I have an ordinary useMutation call, then I want to write:
if (true){
call that useMutation func A
} else {
call that useMutation func B
}
if (true){
call that useMutation func A
} else {
call that useMutation func B
}
But I am getting error Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. More details:
const [connect, setConnect] = useState(false);

const {isLoading: isSending, mutate: handleConnect} =
useMutation(
async () => {
return await connecFunc(token);
},
{
onSuccess: () => {
... sth sth
},
onError: (err: errTypes | any) => {
....sth sth
}
},
},
);

if (connect){
handleConnect();
}

... ...
<ToggleSwitch
selected={connect}
toggleSelected={() => setConnect(!connect)}
positiveText="ON"
negativeText="OFF"
/>
const [connect, setConnect] = useState(false);

const {isLoading: isSending, mutate: handleConnect} =
useMutation(
async () => {
return await connecFunc(token);
},
{
onSuccess: () => {
... sth sth
},
onError: (err: errTypes | any) => {
....sth sth
}
},
},
);

if (connect){
handleConnect();
}

... ...
<ToggleSwitch
selected={connect}
toggleSelected={() => setConnect(!connect)}
positiveText="ON"
negativeText="OFF"
/>
So what is the right way to do this?
5 Replies
conscious-sapphire
conscious-sapphire3y ago
Hey there, it should work as far as I know (based on the code you showed). Can you share more?
rare-sapphire
rare-sapphireOP3y ago
Sure, I will update more code
conscious-sapphire
conscious-sapphire3y ago
oh, that's because you're calling handleConnect() directly inside the render function. So, when connect becomes true, it's called at every render...and it triggers a render etc... If you need to run it when the switch is toggled, call it inside the toggleSelected event handler.
rare-sapphire
rare-sapphireOP3y ago
ohhhhhh... right. Then it only runs when the toggles happens...
conscious-sapphire
conscious-sapphire3y ago
yes!

Did you find this page helpful?