@actualwave/redux-promised-action

0.0.4 • Public • Published

@actualwave/redux-promised-action

Promised action creator factory, uses redux-thunk to return promise from dispatch. It was made to be used with redux-saga but does not depend on it.

Also check redux-promise , official? way to handle promises.

How To

Define action creators:

// actions.js file
import { makeActionCreator, makePromisedActionCreator } from '@actualwave/redux-promised-action';


export const FETCH_DATA = 'FETCH_DATA';
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
export const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';

// returns promise
export const fetchData = makePromisedActionCreator(FETCH_DATA);

// normal action creator, returns nothing
export const fetchDataSuccess = makeActionCreator(FETCH_DATA_SUCCESS);
export const fetchDataFailure = makeActionCreator(FETCH_DATA_FAILURE);

Use action creators:

// react component file
import { connect } from 'react-redux';
import { fetchData } from 'actions';

...

  componentDidMount() {
    const { fetch } = this.props;

    fetch({
	  url: '/api/data',
	}).then(this.handleDataLoaded);
  }

...

export default connect(
  null,
  {
    fetch: fetchData,
  },
)(MyComponent);

Actions created this way contain properties:

  • payload -- its whatever you put into first action creator argument.
  • meta -- its whatever you put into second action creator argument. If action creator was called without arguments, both properties will be empty objects.

For promised action meta object also contains promise with its own Promise returned from action creator, resolve and reject functions to resolve or reject that promise respectively. Take control of the promise in saga function:

function*  fetchDataSaga({ payload: { url }, meta: { resolve, reject } }) {
  try {
    yield put({ type: 'fetchData' });
    const response = yield call(fetchApi, url);
    
	const data = yield call(getDataFromResponse, response);
  
    yield put(fetchDataSuccess(data));
    yield call(resolve, data);
  } catch (error) {
    yield put(fetchDataFailure(error));
    yield call(reject, error);
  }
}

FYI, if you don't use redux-saga and want to achieve same effect with async action creators, using redux-thunk and async/await this approach may suit your needs:

const  fetchData  = ({ payload: { url } }) => async (dispatch) => {
    try {
      dispatch({ type: 'fetchData' });

      const response  =  await fetch(url);

      const data  =  await getDataFromResponse(response);

      dispatch(fetchDataSuccess(data));
      return data;
    } catch (error) {
      dispatch(fetchDataFailure(error));
      throw error;
    }
  };

Written with StackEdit.

Package Sidebar

Install

npm i @actualwave/redux-promised-action

Weekly Downloads

2

Version

0.0.4

License

MIT

Unpacked Size

5.03 kB

Total Files

3

Last publish

Collaborators

  • actualwave