- Notifications
You must be signed in to change notification settings - Fork1
cimdalli/redux-ts
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Utils to define react redux reducer/action in typescript.
npminstall--saveredux-ts
Create redux store with builder pattern.
import{StoreBuilder}from'redux-ts'varstore:Redux.Store<StoreState> = new StoreBuilder<StoreState>().withInitialState({test:true}).withReducersMap(reducers).build();}
Actions store data that are required on reducers. Declaration of them are succeed with es6 decorators so no need to define type again. Depend on need, action could be either sync or async (likeredux-thunk).
import{Action,SyncAction,AsyncAction}from'redux-ts'import{push}from'react-router-redux'@ActionexportclassLoginextendsAsyncAction{constructor(publicusername:string,publicpassword:string){super();}}@ActionexportclassLogoutextendsAsyncAction{}@ActionexportclassSetTokenextendsSyncAction{constructor(publictoken:string){super();}getTokenKey(){return"auth";}}
Unlike original redux implementation, reducers can consume both sync and async actions. Each reducer method should return a value even it doesnt change state. Async operations are stored on async actions and will be resolved after original dispatch cycle is finised.
import{ReducerBuilder}from'redux-ts'import{Login,Logout,SetToken}from'../actions'import{push}from'react-router-redux'exportinterfaceAuthState{token?:string;}exportconstauthReducer=newReducerBuilder<AuthState>().init({}).handle(Login,(state,action)=>{action.then(dispatch=>{fetch(`https://httpbin.org/get?username=${action.username}&password=${action.password}`).then(x=>x.json()).then(data=>{dispatch(newSetToken(data.args.username+"|"+data.args.password));dispatch(push("/dashboard"))});});returnnull;}).handle(Logout,(state,action)=>{action.then(dispatch=>{dispatch(newSetToken(null));dispatch(push("/dashboard"));});returnnull;}).handle(SetToken,(state,action)=>{if(action.token!=null){localStorage.setItem(action.getTokenKey(),action.token);}else{localStorage.removeItem(action.getTokenKey());}return{token:action.token};}).build();
MIT
About
Utils to define react redux reducers/actions in typescript.
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors2
Uh oh!
There was an error while loading.Please reload this page.