Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Sep 11, 2023. It is now read-only.

Dispatching an action handled by redux-saga returns promise

License

NotificationsYou must be signed in to change notification settings

diegohaz/redux-saga-thunk

Repository files navigation

Generated with nodNPM versionNPM downloadsBuild StatusCoverage Status

Dispatching an action handled byredux-saga returns promise. It looks likeredux-thunk, but with pure action creators.

classMyComponentextendsReact.Component{componentWillMount(){    // `doSomething` dispatches an action which is handled by some saga    this.props.doSomething().then((detail)=>{      console.log('Yaay!',detail)    }).catch((error)=>{      console.log('Oops!',error)})}}

redux-saga-thunk usesFlux Standard Action to determine action'spayload,error etc.



If you find this useful, please don't forget to star ⭐️ the repo, as this will help to promote the project.
Follow me onTwitter andGitHub to keep updated about this project andothers.



Motivation

There are two reasons I created this library: Server Side Rendering andredux-form.

When usingredux-saga on server, you will need to know when your actions have been finished so you can send the response to the client. There are several ways to handle that case, andredux-saga-thunk approach is the one I like most. Seean example.

Withredux-form, you need to return a promise fromdispatch inside your submit handler so it will know when the submission is complete. Seean example

Finally, that's a nice way to migrate your codebase fromredux-thunk toredux-saga, since you will not need to change how you dispatch your actions, they will still return promises.

Install

$ npm install --save redux-saga-thunk

Basic setup

Addmiddleware to your redux configuration (before redux-saga middleware):

import{createStore,applyMiddleware}from'redux'importcreateSagaMiddlewarefrom'redux-saga'import{middlewareasthunkMiddleware}from'redux-saga-thunk'^constsagaMiddleware=createSagaMiddleware()conststore=createStore({},applyMiddleware(thunkMiddleware,sagaMiddleware))                                              ^

Usage

You just need to setmeta.thunk totrue on your request actions and put it on your response actions inside the saga:

constaction={  type:'RESOURCE_REQUEST',  payload:{id:'foo'},meta:{thunk:true    ^  }}// send the actionstore.dispatch(action).then((detail)=>{// payload == detailconsole.log('Yaay!',detail)}).catch((e)=>{// payload == econsole.log('Oops!',e)})function*saga(){while(true){    const{ payload, meta}=yieldtake('RESOURCE_REQUEST')                     ^  try{      constdetail=yieldcall(callApi,payload)// payload == { id: 'foo' }yieldput({        type:'RESOURCE_SUCCESS',payload:detail,        meta        ^      })}catch(e){yieldput({type:'RESOURCE_FAILURE',payload:e,error:true,        ^        meta        ^})}}}

redux-saga-thunk will automatically transform your request action and inject akey into it.

You can also use it inside sagas withput.resolve:

function*someSaga(){try{constdetail=yieldput.resolve(action)    console.log('Yaay!',detail)}catch(error){    console.log('Oops!',error)}}

Usage with selectors

To usepending,rejected,fulfilled anddone selectors, you'll need to add thethunkReducer to your store:

import{combineReducers}from'redux'import{reducerasthunkReducer}from'redux-saga-thunk'constreducer=combineReducers({thunk:thunkReducer,// your reducers...})

Now you can use selectors on your containers:

import{pending,rejected,fulfilled,done}from'redux-saga-thunk'constmapStateToProps=state=>({loading:pending(state,'RESOURCE_CREATE_REQUEST'),error:rejected(state,'RESOURCE_CREATE_REQUEST'),success:fulfilled(state,'RESOURCE_CREATE_REQUEST'),done:done(state,'RESOURCE_CREATE_REQUEST'),})

API

Table of Contents

clean

Clean state

Parameters

Examples

constmapDispatchToProps=(dispatch,ownProps)=>({cleanFetchUserStateForAllIds:()=>dispatch(clean('FETCH_USER')),cleanFetchUserStateForSpecifiedId:()=>dispatch(clean('FETCH_USER',ownProps.id)),cleanFetchUsersState:()=>dispatch(clean('FETCH_USERS')),})

pending

Tells if an action is pending

Parameters

Examples

constmapStateToProps=state=>({fooIsPending:pending(state,'FOO'),barForId42IsPending:pending(state,'BAR',42),barForAnyIdIsPending:pending(state,'BAR'),fooOrBazIsPending:pending(state,['FOO','BAZ']),fooOrBarForId42IsPending:pending(state,['FOO',['BAR',42]]),anythingIsPending:pending(state)})

Returnsboolean

rejected

Tells if an action was rejected

Parameters

Examples

constmapStateToProps=state=>({fooWasRejected:rejected(state,'FOO'),barForId42WasRejected:rejected(state,'BAR',42),barForAnyIdWasRejected:rejected(state,'BAR'),fooOrBazWasRejected:rejected(state,['FOO','BAZ']),fooOrBarForId42WasRejected:rejected(state,['FOO',['BAR',42]]),anythingWasRejected:rejected(state)})

Returnsboolean

fulfilled

Tells if an action is fulfilled

Parameters

Examples

constmapStateToProps=state=>({fooIsFulfilled:fulfilled(state,'FOO'),barForId42IsFulfilled:fulfilled(state,'BAR',42),barForAnyIdIsFulfilled:fulfilled(state,'BAR'),fooOrBazIsFulfilled:fulfilled(state,['FOO','BAZ']),fooOrBarForId42IsFulfilled:fulfilled(state,['FOO',['BAR',42]]),anythingIsFulfilled:fulfilled(state)})

Returnsboolean

done

Tells if an action is done

Parameters

Examples

constmapStateToProps=state=>({fooIsDone:done(state,'FOO'),barForId42IsDone:done(state,'BAR',42),barForAnyIdIsDone:done(state,'BAR'),fooOrBazIsDone:done(state,['FOO','BAZ']),fooOrBarForId42IsDone:done(state,['FOO',['BAR',42]]),anythingIsDone:done(state)})

Returnsboolean

License

MIT ©Diego Haz

About

Dispatching an action handled by redux-saga returns promise

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors7


[8]ページ先頭

©2009-2025 Movatter.jp