I am trying to make an API call on changing a state which is triggered by a toggling button in React Native.
For this I have used useEffect to trigger API call.
const GroundFloorLamps = props => {
const [lampsState, setLampsState] = useState({
l1: 'checked',
l2: 'unchecked',
l3: 'unchecked',
l4: 'unchecked',
l5: 'unchecked',
});
const sendState = async () => {
const newState = EncodeLampState(lampsState);
try {
const res = await axios.post(GlobalData.azureFunctions.broadcastUrl, {
state: newState,
});
Log(res.status);
} catch (err) {
Log('Error: \n' + err.message);
}
};
useEffect(() => {
sendState();
}, [lampsState]);
const onToggleSwitch = lampNo => {
setLampsState(prev => ({
...prev,
[lampNo]: prev[lampNo] === 'checked' ? 'unchecked' : 'checked',
}));
};
But on toggling button for the first time, it does not complete the axios.post (not logging the res.status). But at the second toggle it completes both API calls (axios.post). This keep happening for all the even tries and not called in all odd calls.
Please help me if anyone have an idea of this.