redux thunk async action creator code example

Example 1: redux-thunk example

const GET_CURRENT_USER = 'GET_CURRENT_USER';
const GET_CURRENT_USER_SUCCESS = 'GET_CURRENT_USER_SUCCESS';
const GET_CURRENT_USER_FAILURE = 'GET_CURRENT_USER_FAILURE';

const getUser = () => {
  return (dispatch) => {     //nameless functions
    // Initial action dispatched
    dispatch({ type: GET_CURRENT_USER });
    // Return promise with success and failure actions
    return axios.get('/api/auth/user').then(  
      user => dispatch({ type: GET_CURRENT_USER_SUCCESS, user }),
      err => dispatch({ type: GET_CURRENT_USER_FAILURE, err })
    );
  };
};

Example 2: redux-thunk example

const INCREMENT_COUNTER = 'INCREMENT_COUNTER';

function increment() {
  return {
    type: INCREMENT_COUNTER
  };
}

function incrementAsync() {
  return dispatch => {
    setTimeout(() => {
      // You can invoke sync or async actions with `dispatch`
      dispatch(increment());
    }, 1000);
  };
}

Example 3: redux-thunk action creator

/* Redux-Thunk Action Creator */
const createAction = () => { type: 'ACTION_TYPE' };

function createAsyncAction() {
	return (dispatch) => {
		setTimeout(() => {
      		dispatch(createAction());
          	/* ^ invoke sync or async actions with dispatch */
    	}, 1000);
	}
}

/* About Redux-Thunk Actions
 * redux-thunk allows you to write action creators
 * that return a function instead of an action
 */