Consider the code below
App.js:
function user_getUser() {
return dispatch => {
dispatch({ type: "GET_USER" })
}
}
function user_getCustomer() {
return dispatch => {
dispatch({ type: "GET_CUSTOMER" })
}
}
class App extends React.Component {
render() {
return (
<div>Hello world !</div>
)
}
}
function mapStateToProps(state) {
return {}
}
function mapDispatchToProps(dispatch) {
return {
getUser: () => dispatch(user_getUser()),
getCustomer: () => dispatch(user_getCustomer()),
}
}
ReactRedux.connect(mapStateToProps, mapDispatchToProps)(App)
ReactDOM.render(<App />, document.getElementById('root'));
I simplified the code but normally getUser() and getCustomer() get JSON objects from an api. I would like to execute getCustomer() when the api responsed to getUser().
Is it possible?
PS: I'm a beginner with reactJS so be indulgent
You should use Redux Thunk. It will let you run async code and then you could chain your functions. Another nice thing that you could do with it is check your store's state in the actions in case you need for example something from the store AFTER the first call has been completed.
Side note - Maybe you could refactor the server side to bring you both pieces of data together and then you could do it in 1 API call without having to wait until 1 finishes and then start the next.
2nd Side Note - If the calls are not necessarily dependent on each other, maybe use something like Promise.all?
Promise.all([user_getUser(), user_getCustomer()]
.then(([user, customer]) => {
dispatch(...)
});
Related
I have a redux saga setup which works fine. One of my dispatches is to create a new order, then once that has been created I want to do things with the updated state.
// this.props.userOrders = []
dispatch(actions.createOrder(object))
doSomethingWith(this.props.userOrders)
Since the createOrder action triggers a redux saga which calls an API, there is a delay, so this.props.userOrders is not updated before my function doSomethingWith is called. I could set a timeout, but that doesn't seem like a sustainable idea.
I have read the similar questions on Stack Overflow, and have tried implementing the methods where relevant, but I can't seem to get it working. I'm hoping with my code below that someone can just add a couple of lines which will do it.
Here are the relevant other files:
actions.js
export const createUserOrder = (data) => ({
type: 'CREATE_USER_ORDER',
data
})
Sagas.js
function * createUserOrder () {
yield takeEvery('CREATE_USER_ORDER', callCreateUserOrder)
}
export function * callCreateUserOrder (newUserOrderAction) {
try {
const data = newUserOrderAction.data
const newUserOrder = yield call(api.createUserOrder, data)
yield put({type: 'CREATE_USER_ORDER_SUCCEEDED', newUserOrder: newUserOrder})
} catch (error) {
yield put({type: 'CREATE_USER_ORDER_FAILED', error})
}
}
Api.js
export const createUserOrder = (data) => new Promise((resolve, reject) => {
api.post('/userOrders/', data, {headers: {'Content-Type': 'application/json'}})
.then((response) => {
if (!response.ok) {
reject(response)
} else {
resolve(data)
}
})
})
orders reducer:
case 'CREATE_USER_ORDER_SUCCEEDED':
if (action.newUserOrder) {
let newArray = state.slice()
newArray.push(action.newUserOrder)
return newArray
} else {
return state
}
This feels like an XY Problem. You shouldn't be "waiting" inside a component's lifecycle function / event handler at any point, but rather make use of the current state of the store.
If I understand correctly, this is your current flow:
You dispatch an action CREATE_USER_ORDER in your React component. This action is consumed by your callCreateUserOrder saga. When your create order saga is complete, it dispatches another "completed" action, which you already have as CREATE_USER_ORDER_SUCCEEDED.
What you should now add is the proper reducer/selector to handle your CREATE_USER_ORDER_SUCCEEDED:
This CREATE_USER_ORDER_SUCCEEDED action should be handled by your reducer to create a new state where some "orders" property in your state is populated. This can be connected directly to your component via a selector, at which point your component will be re-rendered and this.props.userOrders is populated.
Example:
component
class OrderList extends React.PureComponent {
static propTypes = {
userOrders: PropTypes.array.isRequired,
createOrder: PropTypes.func.isRequired,
}
addOrder() {
this.props.createOrder({...})
}
render() {
return (
<Wrapper>
<Button onClick={this.addOrder}>Add Order</Button>
<List>{this.props.userOrders.map(order => <Item>{order.name}</Item>)}</List>
</Wrapper>
)
}
}
const mapStateToProps = state => ({
userOrders: state.get('userOrders'),
})
const mapDispatchToProps = {
createOrder: () => ({ type: 'CREATE_ORDER', payload: {} }),
}
export default connect(mapStateToProps, mapDispatchToProps)(OrderList)
reducer
case 'CREATE_USER_ORDER_SUCCEEDED':
return state.update('userOrders',
orders => orders.concat([payload.newUserOrder])
)
If you really do need side-effects, then add those side-effects to your saga, or create a new saga that takes the SUCCESS action.
I'm a Jest/React beginner. In jest's it I need to wait until all promises have executed before actually checking.
My code is similar to this:
export class MyComponent extends Component {
constructor(props) {
super(props);
this.state = { /* Some state */ };
}
componentDidMount() {
fetch(some_url)
.then(response => response.json())
.then(json => this.setState(some_state);
}
render() {
// Do some rendering based on the state
}
}
When the component is mounted, render() runs twice: once after the constructor runs, and once after fetch() (in componentDidMount()) finishes and the chained promises finish executing).
My testing code is similar to this:
describe('MyComponent', () => {
fetchMock.get('*', some_response);
it('renders something', () => {
let wrapper = mount(<MyComponent />);
expect(wrapper.find(...)).to.have.something();
};
}
Whatever I return from it, it runs after the first time render() executes but before the second time. If, for example, I return fetchMock.flush().then(() => expect(...)), the returned promise executes before the second call to render() (I believe I can understand why).
How can I wait until the second time render() is called before running expect()?
I'd separate concerns, mainly because is easier to maintain and to test. Instead of declaring the fetch inside the component I'd do it somewhere else, for example in a redux action (if using redux).
Then test individually the fetch and the component, after all this is unit testing.
For async tests you can use the done parameter on the test. For example:
describe('Some tests', () => {
fetchMock.get('*', some_response);
it('should fetch data', (done) => { // <---- Param
fetchSomething({ some: 'Params' })
.then(result => {
expect(result).toBe({ whatever: 'here' });
done(); // <--- When you are done
});
});
})
The you can tests your component by just sending the loaded data in the props.
describe('MyComponent', () => {
it('renders something', () => {
const mockResponse = { some: 'data' };
let wrapper = mount(<MyComponent data={mockResponse}/>);
expect(wrapper.find(...)).to.have.something();
});
});
When it comes to testing you need to keep it simple, if your component is difficult to test, then there's something wrong with your design ;)
I've had some success with this, as it doesn't require wrapping or modifying components. It is however assuming there's only one fetch() in the component, but it can be easily modified if needed.
// testhelper.js
class testhelper
{
static async waitUntil(fnWait) {
return new Promise((resolve, reject) => {
let count = 0;
function check() {
if (++count > 20) {
reject(new TypeError('Timeout waiting for fetch call to begin'));
return;
}
if (fnWait()) resolve();
setTimeout(check, 10);
}
check();
});
}
static async waitForFetch(fetchMock)
{
// Wait until at least one fetch() call has started.
await this.waitUntil(() => fetchMock.called());
// Wait until active fetch calls have completed.
await fetchMock.flush();
}
}
export default testhelper;
Then you can use it just before your assertions:
import testhelper from './testhelper.js';
it('example', async () => {
const wrapper = mount(<MyComponent/>);
// Wait until all fetch() calls have completed
await testhelper.waitForFetch(fetchMock);
expect(wrapper.html()).toMatchSnapshot();
});
I found a way to do what I originally asked. I have no opinion (yet) whether it is good strategy or not (in fact I had to refactor the component immediately afterwards, so this question is no longer relevant to what I'm doing). Anyway, here is the testing code (explanation below):
import React from 'react';
import { mount } from 'enzyme';
import { MyComponent } from 'wherever';
import fetchMock from 'fetch-mock';
let _resolveHoldingPromise = false;
class WrappedMyComponent extends MyComponent {
render() {
const result = super.render();
_resolveHoldingPromise && _resolveHoldingPromise();
_resolveHoldingPromise = false;
return result;
}
static waitUntilRender() {
// Create a promise that can be manually resolved
let _holdingPromise = new Promise(resolve =>
_resolveHoldingPromise = resolve);
// Return a promise that will resolve when the component renders
return Promise.all([_holdingPromise]);
}
}
describe('MyComponent', () => {
fetchMock.get('*', 'some_response');
const onError = () => { throw 'Internal test error'; };
it('renders MyComponent appropriately', done => {
let component = <WrappedMyComponent />;
let wrapper = mount(component);
WrappedMyComponent.waitUntilRender().then(
() => {
expect(wrapper.find('whatever')).toBe('whatever');
done();
},
onError);
});
});
The main idea is that, in the testing code, I subclass the component (if this was Python I'd probably monkey-patch it, which works more or less the same way in this case) so that its render() method sends a signal that it executed. The way to send the signal is by manually resolving a promise. When a promise is created, it creates two functions, resolve and reject, which when called terminate the promise. The way to have code outside the promise resolve the promise is by having the promise store a reference to its resolve function in an external variable.
Thanks to fetch-mock author Rhys Evans who kindly explained the manually-resolve-promise trick to me.
I have a fairly simple use case, but having a hard to find the appropriate answer. I'm using React,Redux,React Router & redux thunk middleware.
Lets say, I have two module food-tags & food. These modules have individual create,list,edit page/component. In practical use case, food-tags have no special value. Whenever a food object is created, separated tags are inserted into the food object's tags property.
General use case is that, after any item is created successfully, react router redirects it to the list page.
whenever i'm calling the createTag action from food-tag module, I can do it in a hacky way. like just after the success dispatch, i can call
browserHistory.push('/dashboard/tags')
this leads me to a problem where i can create food-tag inline from the food create component. Codes are given below
actions.js
export function createTag(tag) {
return function (dispatch) {
axios.post(API_URL + 'api/tags', tag)
.then((response) => {
// I CAN DO REDIRECT HERE,BUT THIS CAUSES THE PROBLEM
dispatch({type: 'TAG_CREATE_RESOLVED', payload:response});
toastr.success('Tag created Successfully.......!');
})
.catch((err) => {
dispatch({type: 'TAG_CREATE_REJECTED', payload: err});
toastr.warning(err.message);
})
}
}
component/container.js
createTag () {
//validatation & others....
this.props.createTag(tag)
}
react-redux connection
function mapDispatchToProps (dispatch) {
return bindActionCreators({
createTag: createTag
}, dispatch)
}
Almost same pattern in food/create.js
$('#food-tags').select2(select2settings).on('select2:selecting', function (event) {
let isNewTagCreated = event.params.args.data.newOption,
name = event.params.args.data.text;
if (isNewTagCreated && name !== '') {
reactDOM.props.createTag({name}); // reactDOM = this context here
}
});
What I want basically that, I want to get access in the component level which action type is dispatching so that i can redirect from component & show notifications as well instead of action thunk. May be i'm not thinking in the proper way. there could be a dead simple work around.
It's good to know that redux-thunk passed out return value from the function. So you can return the promise from the action creator and wait until it will be finished in you component code
export function createTag(tag) {
return function (dispatch) {
return axios.post(API_URL + 'api/tags', tag) // return value is important here
.then((response) => dispatch({type: 'TAG_CREATE_RESOLVED', payload:response}))
.catch((err) => {
dispatch({type: 'TAG_CREATE_REJECTED', payload: err})
throw err; // you need to throw again to make it possible add more error handlers in component
})
}
}
Then in your component code
createTag () {
this.props.createTag(tag)
.then(() => {
toastr.success('Tag created Successfully.......!');
this.props.router.push() // I assume that you have wrapped into `withRouter`
})
.catch(err => {
toastr.warning(err.message);
});
}
Now you have proper split up between action logic and user interface.
I'm trying to leverage a firebase observable from within the redux-sagas framework but I'm having trouble doing this without a hack. I'm trying to use firebase's "onAuthStateChange" function as shown here
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
essentially the observer executes whenever a user signs in or out
In my firebase utility file my method looks like this:
authChanged: () =>{
return firebaseAuth.onAuthStateChanged(callback);
}
then in my saga, for the moment, I'm simply trying to log to the console whenever the observer observes something:
export function* loginState(){
Firebaseutils.authChanged(function(user){
if(user){
console.log('User logged in!')
}else{
console.log('User logged out')
}
});
}
This fails due to 'callback' not being defined. I'm essentially trying to curry the observer to pass to sagas but it's not working. My workaround is to pass the full firebase auth object to my login/logout saga and then create the observer in there. That works but seems like a hack. Any help would be hugely appreciated.
I don't think you're actually integrating the observer into the saga in your snippet. It'll work for console.log b/c that's a sync function, but you can't yield anything from that callback, as its context is separate from that of the generator. this deprives you of lots of the sagas utility, if it works # all.
I had to get this working on my project, and the best I could do was inspired by this project and the architecture in this starter-kit.
Basically,it's a few steps.
Wrap your observer in function that takes dispatch and returns a promise.
export function initAuth(dispatch) {
return new Promise((resolve, reject) => {
myFirebaseAuthObj.onAuthStateChanged(
authUser => {
if (authUser) {
dispatch(signInFulfilled(authUser))
} else if (authUser === null) {
dispatch(signOutFulfilled())
}
resolve()
},
error => reject(error)
)
})
}
Wrap your top-level container in a function
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState)
let render = () => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
wrap render() in initAuth:
initAuth(store.dispatch)
.then(() => render())
.catch(error => console.error(error))
use your sagas for anything else. for example, you can conduct route-changes from your sagas like so:
function* signIn(authProvider) {
try {
const authData = yield call([firebaseAuth, firebaseAuth.signInWithPopup], authProvider)
yield take(SIGN_IN_FULFILLED)
browserHistory.push('/dash')
}
catch (error) {
yield put(signInFailed(error))
}
}
It seems like you meant to have callback as a parameter to authChanged but authChanged currently takes no parameters. Here's what you probably meant to do:
authChanged: (callback) => {
return firebaseAuth.onAuthStateChanged(callback);
}
I'm not sure I understand what you mean by currying the observer but you could also do something like this to curry the firebase method to use as your method:
{
authChanged: ::firebaseAuth.onAuthStateChanged,
}
In my React App I need to take decision based on data I receive from the server.
If data is expected ( Dispatch actions to update state)
If data has error tag ( browserhistory.push('/notfound'); )
If expected data is unable to parsed ( browserhistory.push('/error');)
In my app structure, I am using Redux, React-Router and React-redux-Router libraries but no middleware. I have made actionHelpers to making ajax calls and then dispatch appropriate actions using Action Creator. These actionHelper methods are exposed in Components to change state.
My Questions:
What's the best way to handle these scenarios ?
Is actionHelper the best place to take these decisions ?
I don't want to use any middleware for now but please let me know if its a good idea to use middleware to handle these scenarios.
Actions are not the place where you should do redirections. This behavior should be implemented in the component itself and actions should be left to update the store.
You may want to use the Redux-thunk middleware here which allows you to dispatch a function (which receives dispatch as an argument instead of the object actions. You can then wrap that function in a promise and use it in componentWillMount.
In your actions file:
updateReduxStore(data) {
return {
type: SOME_TYPE,
payload: data.something
};
}
fetchAndValidateData() {
...
}
checkData() {
return function(dispatch) {
return new Promise((resolve, reject) => {
fetchAndValidateData().then((data) => {
try {
if (JSON.parse(data).length > 0) {
dispatch(updateReduxStore(data));
resolve('valid data');
} else if (data.error) {
reject('error in data');
}
}
catch(err) {
reject('malformed data');
}
});
});
};
}
Then in your component:
componentWillMount() {
this.props.checkData()
.then((message) => {
console.log(message); //valid data
})
.catch((err) => {
if (err === 'error in data') {
browserHistory.push('/notfound');
} else if (err === 'malformed data') {
browserHistory.push('/error');
}
});
}
Redux-thunk middleware is made for such use cases.