Redux Reducer is being called twice, leading to error

Viewed 27

I am using Redux with middleware and multiple reducers. My store.js looks like this:

const reducer = combineReducers({
  userReducer,
  watchListReducer,
  itemsReducer,
});

export const CombinedStore = createStore(reducer, applyMiddleware(thunk));

And I use it like so in App.tsx

<Provider store={CombinedStore}>
// my app
</Provider>

I have the following function which fetches relevant UserData:



const loadUserDataRedux = async () => {
    setLoading(true);

    let userBuilder = new OnlineUserBuilder();

    if (authData) {
      await userBuilder.initialize();
      await userBuilder.setProfile();
      await userBuilder.setInventory();
      await userBuilder.setAdditionalInfo();
      await userBuilder.setWatchLists();
      await userBuilder.setOfflineData();
      let user = userBuilder.build();

      setUserData(user); 
      console.log("calling redux");
      dispatch(setUser(user));
    }
    setLoading(false);
  };

This method is being called intentionally in useEffect of my App.tsx.

Actions.js

export const setUser = (user: UserData) => (dispatch: any) => {
  dispatch({
    type: SET_USER,
    payload: user,
  });
};

Reducer.js

case SET_USER:
      console.log("-->", action.payload.id);
      return { ...state, user: action.payload };

so the output looks like this:

... other output ...
calling redux
--> 123434567
... other output ...
--> undefined

Expected:

... other output ...
calling redux"
--> 123434567
... other output ...

At some places, I use the data of user by using useSelector. But somehow, console.log() inside Reducer.js is called twice. The first time, everything is fine and the data is being displayed correctly, but with a delay of ca. 1 sec, Reducer.js is being called again, but obviously without any payload, which results in empty redux store.

I have read, that this is the expected behaviour for redux and I tried using `React.StrictMode´ but not working.

This cant be the desired behaviour for Redux, right??

0 Answers
Related