0

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.

1 Answers1

0

React compares objects with their reference. This may affect its behavior in these cases- 1- Object is exactly the same, but compared using different references. 2- Object with different values, but compared with the same reference.

So, in your case, your lamp state is an object

    const [lampsState, setLampsState] = useState({
    l1: 'checked',
    l2: 'unchecked',
    l3: 'unchecked',
    l4: 'unchecked',
    l5: 'unchecked',
  });

there can be side effects due to it while detecting the lampstate change.

so, as to work one way , you can update your useeffect dependency array as

useEffect(() => {
    sendState();
  }, [lampsState.l1,lampsState.l2,lampsState.l3,lampsState.l4,lampsState.l5]);

or other ways you can use Memoizing of object etc,

Refer this for more info

  • Great thanks for your help, **But** the problem still persist after applying your solution of dependancy array. – Umeshan Weerasekara Jun 26 '22 at 04:51
  • Interpreter comes to axios.post and not giving a response or catch any error in the **first** change of state. But gives both responses at the **second** change of state. – Umeshan Weerasekara Jun 26 '22 at 04:54
  • that's strange. You can try checking the API responses with reactotron or flipper , to check the responses are as expected in accordance with the changes – Chundru Teja Jun 26 '22 at 16:07