lundi 28 septembre 2020

Will moving code from a thunk to a custom hook make my app's code harder to test?

When my app first renders, I need to set up some listeners (authentication listener and some global data that is necessary from the first render).

The stack I'm using: react, redux (thunks) and firebase.

I need to decide between the 2 following patterns on how to set up those listeners:

OPTION #1

Treat it as a regular thunk.

APP_THUNKS.ts

export const setAuthListener = (): APP_THUNK => {
  return async (dispatch,getState) => {
    // CODE TO LISTEN TO THE auth OBJECT FROM firebase
    // AND UPDATE THE STATE ON EVERY NEW snapshot
    dispatch(ACTIONS.UPDATE_AUTH(auth));
  };
};

App.tsx

const dispatch = useDispatch();

useEffect(() => {
  dispatch(setAuthListener());
},[dispatch]);

OPTION #2

Move the thunk code to a custom hook called: useAuthListener(). Example:

useAuthListener.ts

export const useAuthListener = () => {

  const dispatch = useDispatch();

  // BASICALLY I'LL RUN THE CODE FROM THE THUNK ABOVE IN THE FOLLOWING useEffect

  useEffect(() => {
    // CODE TO LISTEN TO THE auth OBJECT FROM firebase
    // AND UPDATE THE STATE ON EVERY NEW snapshot
    dispatch(ACTIONS.UPDATE_AUTH(auth));
  },[dispatch]);

};

Is one option better than the other? I'm asking this because I know this pattern might influence the "testability" of my code in the future, and I don't have much experience with testing. Should I favor one of these patterns over the other?

Aucun commentaire:

Enregistrer un commentaire