'Axios calls with React : best practises

i want to know if there is some clean code or update to make it on my code, because i think i repeat the same code on every actions on my redux, my question is how can I avoid calling axios on my actions files ?

Please take a look on my code here :

export const SignInType = (host, lang) => async (dispatch) => {
    try {
        dispatch({
            type: USER_LOGIN_SIGNINTYPE_REQUEST,
        });

        const { data } = await axios.get(
            `/${lang}/data?host=${host}`
        );
        console.log({ data });
        dispatch({
            type: USER_LOGIN_SIGNINTYPE_SUCCESS,
            payload: data,
        });
        dispatch({
            type: USER_LOGIN_CLEAR_ERROR,
        });
    } catch (err) {
        dispatch({
            type: USER_LOGIN_SIGNINTYPE_FAIL,
            payload: err,
        });
    }
};

I Really want to delete the Axios name from my actions file and make it on a separate file, but how can i do this ? Thank you



Solution 1:[1]

We can suggest but there's no correct answer to this, initially any redundant lines of code can be abstracted, so in order to make things a little bit easier, we need to abstract the obvious and add the meaningful, e.g:

abstract the way you write action creators:

const actionComposer = (options) => (...args) => async dispatch => {
  const modifiedDispatch = (type, payload) => dispatch({ type, payload });
  const { action, onSuccess, onFailed } = options(modifiedDispatch);
  try {
    if (action) {
      const res = await action(...args)
      onSuccess(res);
    }
  } catch (err) {
    onFailed(err)
  }
}

then your code can look like this:

export const SignInType = actionComposer((dispatch)=> {
  return {
    action: async (host, lang) => {
      dispatch(USER_LOGIN_SIGNINTYPE_REQUEST);
      const { data } = await axios.get(`/${lang}/data?host=${host}`);
      return data;
    },
    onSuccess: (res) => {
      dispatch(USER_LOGIN_SIGNINTYPE_SUCCESS, data);
      dispatch(USER_LOGIN_CLEAR_ERROR);
    },
    onFailed: (err) => {
      dispatch(USER_LOGIN_CLEAR_ERROR, err.message)
    }
  }
})

Solution 2:[2]

Redux Toolkit already has a createAsyncThunk API that does all the work of defining the action types and dispatching them for you. You should use that.

Alternately, you can use our RTK Query data fetching and caching library, which will eliminate the need to write any data fetching logic yourself.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eslam abed ElRahman
Solution 2 markerikson