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

TypeScript FSA utilities for redux-thunk - shamelessly based on typescript-fsa-redux-saga and ...

License

NotificationsYou must be signed in to change notification settings

xdave/typescript-fsa-redux-thunk

Repository files navigation

TypeScript FSA utilities for redux-thunk

npm (tag)npmGitHub last commit (branch)Build Statuscodecov

NOTE: There's breaking changes from 1.x. Read on to find out more and check the notes at the bottom for more info

Installation

npm install typescript-fsa-redux-thunk redux redux-thunk

API

thunkToAction(ThunkActionCreator): ((Params) => Result)

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!

react-redux integrated

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

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors4

  •  
  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp