- Notifications
You must be signed in to change notification settings - Fork9
TypeScript FSA utilities for redux-thunk - shamelessly based on typescript-fsa-redux-saga and ...
License
xdave/typescript-fsa-redux-thunk
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
TypeScript FSA utilities for redux-thunk
NOTE: There's breaking changes from 1.x. Read on to find out more and check the notes at the bottom for more info
npm install typescript-fsa-redux-thunk redux redux-thunk
Another useful cast function that can help when attempting to extract the returnvalue out of your async action creator. If the action is being pre-bound todispatch, then all we want back is the return value (the action object).Coming soon: an example. TL;DR: pass your async action creator into this beforepassing it tobindActionCreators or themapDispatchToProps object (react-redux).
asyncFactory<State>(ActionCreatorFactory): ((type: string, AsyncWorker) => ({ (params?): ThunkActionCreator, async: AsyncActionCreators }))
Factory function to easily create a typescript-fsa redux thunk.
Example
import'isomorphic-fetch';import{createStore,applyMiddleware,AnyAction}from'redux';importthunkMiddleware,{ThunkMiddleware}from'redux-thunk';import{reducerWithInitialState}from'typescript-fsa-reducers';importactionCreatorFactoryfrom'typescript-fsa';import{asyncFactory}from'typescript-fsa-redux-thunk';/** You can optionally use custom Error types */classCustomErrorextendsError{}/** Parameters used for logging in */interfaceLoginParams{email:string;password:string;}/** The object that comes back from the server on successful login */interfaceUserToken{token:string;}/** The shape of our Redux store's state */interfaceState{title:string;userToken:UserToken;loggingIn?:boolean;error?:CustomError;}/** The typescript-fsa action creator factory function */constcreate=actionCreatorFactory('examples');/** The typescript-fsa-redux-thunk async action creator factory function */constcreateAsync=asyncFactory<State>(create);/** Normal synchronous action */constchangeTitle=create<string>('Change the title');/** The asynchronous login action; Error type is optional */constlogin=createAsync<LoginParams,UserToken,CustomError>('Login',async(params,dispatch)=>{consturl=`https://reqres.in/api/login`;constoptions:RequestInit={method:'POST',body:JSON.stringify(params),headers:{'Content-Type':'application/json; charset=utf-8',},};constres=awaitfetch(url,options);if(!res.ok){thrownewCustomError(`Error${res.status}:${res.statusText}`);}dispatch(changeTitle('You are logged-in'));returnres.json();},);/** An initial value for the application state */constinitial:State={title:'Please login',userToken:{token:'',},};/** Reducer, handling updates to indicate logging-in status/error */constreducer=reducerWithInitialState(initial).case(changeTitle,(state,title)=>({ ...state, title,})).case(login.async.started,(state)=>({ ...state,loggingIn:true,error:undefined,})).case(login.async.failed,(state,{ error})=>({ ...state,loggingIn:false, error,})).case(login.async.done,(state,{result:userToken})=>({ ...state, userToken,loggingIn:false,error:undefined,}));/** Putting it all together */(async()=>{// Declaring the type of the redux-thunk middleware is what makes// `store.dispatch` work. (redux@4.x, redux-thunk@2.3.x)constthunk:ThunkMiddleware<State,AnyAction>=thunkMiddleware;conststore=createStore(reducer,applyMiddleware(thunk));console.log(store.getState().title);try{// See https://reqres.in/api/users for valid users on this siteawaitstore.dispatch(login({email:'eve.holt@reqres.in',password:'cityslicka',}),);const{ title, userToken}=store.getState();console.log(title,userToken);}catch(err){console.log(err);}})();
Note: A change from 1.x is the result type is not always assumed to be aPromise. If you want the result to be a promise, just return one from yourworker function; but continue to specify the result asT rather thanPromise<T> (same as 1.x).
The API has been simplified. This release is in preparation for a new projectthat works with react hooks. Coming soon!
import{ThunkDispatch,AnyAction}from'redux-thunk';import{RootState}from'to/your/reducers';declare module'react-redux'{interfaceDefaultRootStateextendsRootState{}functionuseDispatch():ThunkDispatch<RootState,never,AnyAction>;}declare module'typescript-fsa-redux-thunk'{interfaceDefaultRootStateextendsRootState{}}
About
TypeScript FSA utilities for redux-thunk - shamelessly based on typescript-fsa-redux-saga and ...
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.