93

redux-thunk-generators

 6 years ago
source link: https://www.npmjs.com/package/redux-thunk-generators
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Redux thunk + generators

You can use generators as action creators or thunks. Fully compartible with redux-thunk!

NPM Downloads

Installation

npm install --save redux-thunk-generators

Just replace redux-thunk import with redux-thunk-generators

Usage

You can use generators (sync or async) as thunks:

export const signIn = payload => async function* (dispatch, getState, extraArgument) { /* ... */ }

Or use generators as action creators:

export const signIn = async function* (payload) { /* ... */ }

Yield action objects to dispatch them! Forget about wrapping each time with dispatch:

// Action creator
export const signIn = async function* (payload) {
  const { username, password } = payload;
  let state = yield; // won't be dispatched, just returns current state
  yield signInStart();
    const response = await axios.post(API_SIGN_IN, { username, password });
    yield signInEnd();
    yield signInSuccess(response.data);
    return username;
  } catch (error) {
    yield signInEnd();
    yield signInError(error);

yield always returns a (new) state.

If you want to do something when your action is done, return some data from generator and get it with .then:

signIn().then(username => {
  console.log(username)

Yep, nice) Tell your friend.

Author

@doasync


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK