Redux Action and Reducer creator.
npm install --save redux-all-creator
- test
$ yarn
$ yarn test
import * as ReduxCreator from 'redux-all-creator';
// hello.js
export default ReduxCreator.create({
namespace: 'hello',
actions: {
hello: ReduxCreator.createAction((data) => {
return `Hello ${data}`;
})
},
reducers: {
hello: ReduxCreator.createReducer((on, actions) => {
on(actions.hello).completed((state, action) => {
return action.payload;
})
}, '')
}
});
// or pure hello.js
export default ReduxCreator.create({
namespace: 'hello',
actions: {
hello: (data) => {
return `Hello ${data}`;
}
},
reducers: {
hello: (on, actions) => {
on(actions.hello).completed((state, action) => {
return action.payload;
})
} // initialState is {}
}
});
Connect all creators and get reducers object.
import * as ReduxCreator from 'redux-all-creator';
import HelloCreator from './examples/hello';
// create connector
const connector = ReduxCreator.connect(HelloCreator, ...);
// create redux store
const middlewares = [];
const store = Redux.createStore(
Redux.combineReducers(connector.getReducers()),
Redux.applyMiddleware(...middlewares)
);
// jest test
it('hello world', () => {
const data = 'Redux Creator';
store.dispatch(HelloCreator.hello(data))
// hello is reduce key
expect(store.getState().hello).toBe(`Hello ${data}`);
})
- More Examples OR
__tests__ directory
.
You can get status(true or false) before and after Fetch(Promise) action. You should also use redux-promise.
- import middleware
import promiseMiddleware from 'redux-promise';
import * as ReduxCreator from 'redux-all-creator';
const middlewares = [ ReduxCreator.fetchStatusMiddleware, promiseMiddleware ];
- create action and reducer
// promise.js
// delay方法
const delay = (time) => (result) => new Promise(resolve => setTimeout(() => resolve(result), time));
// !!! important: add fetch property to true
export default ReduxCreator.create({
namespace: 'TestPromise',
actions: {
promiseStatus: ReduxCreator.createAction((id) => {
return Promise.resolve({ body: `Promise Status ${id}` }).then(delay(2000)).then(res => res.body)
}, { fetch: true })
},
reducers: {
promise: ReduxCreator.createReducer((on, actions) => {
on(actions.promiseStatus).completed((state, action) => {
return action.payload;
});
}, {})
}
});
- get fetch status
import PromiseCreator from './example/promise';
it('test promise status', (done) => {
const id = 1;
store.dispatch(PromiseCreator.promiseStatus(id))
.then(it => {
const state = store.getState();
expect(state.promise).toBe(`Promise Status ${id}`);
// fetch end
const fetchStatus = ReduxCreator.getFetchStatus(state, PromiseCreator.promiseStatus);
expect(fetchStatus).toBe(false);
done();
});
// fetch start
const state = store.getState();
const fetchStatus = ReduxCreator.getFetchStatus(state, PromiseCreator.promiseStatus)
expect(fetchStatus).toBe(true);
})
- Promise data cache
- Connect with React