Skip to content

Instantly share code, notes, and snippets.

@LucaColonnello
Last active January 16, 2016 11:05
Show Gist options
  • Save LucaColonnello/b802d9eef31e807b60d4 to your computer and use it in GitHub Desktop.
Save LucaColonnello/b802d9eef31e807b60d4 to your computer and use it in GitHub Desktop.
Redux Async Actions Utils
// react component
class MyComponent extends Rect.Component {
render( ) {
const {
ready,
downloadTodosHasDone,
downloadTodosState,
errors,
todos
} = this.props;
if( ready ) {
if( errors ) {
// render error message
} else {
// render component...
}
} else {
// loading
}
}
}
function mapStateToProps( state ) {
const asyncActionsState = createAsyncActionsState(
state,
// if not specifed,
// get all async actions state in the store
DOWNLOAD_TODOS,
// use optionalAsyncAction to optionally check an action
// this action will be checked if it will call
// if it will not call, the asyncActionState will not check
// for it inside hasDone call ('cause it doesn't exists).
// optionalAsyncAction( SYNC_TODOS_REMOTE )
// if an action will be checked not as an optional one,
// the system will wait until action will be called,
// so hasDone doesn't give true
);
/*
asyncActionsState: {
DOWNLOAD_TODOS: AsyncState Object,
// in the prototype, so that it isn't Iterable
hasDone: function( [action type] ): Bool
// return errors array
getErrors: function( ): Array<Error>
}
*/
return {
ready: asyncActionsState.hasDone( ),
downloadTodosHasDone: asyncActionsState.hasDone( DOWNLOAD_TODOS ),
downloadTodosState: asyncActionsState[ DOWNLOAD_TODOS ],
errors: asyncActionsState.getErrors( ).length,
todos: state.todos,
};
}
export connect( mapStateToProps )( MyComponent );
// store creation
import {
createStore,
combineReducers
} from 'redux'
import {
asyncActionsState
} from 'redux-async-utils'
let store = createStore( combineReducers(
asyncActionsState,
todos
) );
// duck module todo
import {
pendingActionCreator,
successActionCreator,
failureActionCreator,
} from 'redux-async-utils';
// action
const DOWNLOAD_TODOS = 'DOWNLOAD_TODOS';
const SET_TODOS = 'SET_TODOS';
function downloadTodos( ) {
return (dispatch, getState) => {
dispatch(
pendingActionCreator( DOWNLOAD_TODOS )
);
setTimeout( () => {
dispatch(
successActionCreator(
DOWNLOAD_TODOS,
{
type: SET_TODOS,
todos: [
{
description: 'Something...',
done: false,
},
]
}
)
);
}, 3000 );
};
}
// reducer
function todos( state = initialState, action ) {
let todos = state;
switch( action.type ) {
case SET_TODOS:
todos = action.todos;
break;
}
return todos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment