Search code examples
javascriptaxiosredux-thunk

Invoking an async action creator helper with redux-thunk


I'm trying to invoke a helper method for two async action creators, but I'm unsure why I can't do so. The function assigned to signUpOrSignIn should get invoked by both signUp andsignIn. These are in the same file. I'm thinking the issue involves either my function declaration or handling of async dispatch. Would appreciate your feedback. Thanks!

import axios from "axios";
import * as types from "./types";

const signUpOrSignIn = (path, email, password, history) => async dispatch => {
  try {
    const res = await axios.post(path, { email, password });
    history.push("/dashboard");
    dispatch({ type: types.DID_SIGN_IN, payload: res });
  } catch (err) {
    dispatch({ type: types.DID_SIGN_IN, payload: err.response });
  }
};

export const signUp = (email, password, history) => async dispatch => {
  signUpOrSignIn("/users", email, password, history);
};

export const signIn = (email, password, history) => async dispatch => {
  signUpOrSignIn("/users/login", email, password, history);
};

Solution

  • Since signUp or signIn intend to just return the signUpOrSignIn.

    You can remove async dispatch.

    Like so:

    export const signUp = (email, password, history) => signUpOrSignIn("/users", email, password, history);
    
    export const signIn = (email, password, history) => signUpOrSignIn("/users/login", email, password, history);