Reputation: 1039
So, my current code looks something like this:
component:
requestDescriptions(params, bothGender) {
if (bothGender) {
// men request
params.gender = 'men';
this.props.getDescriptions(params);
// women request
params.gender = 'women';
this.props.getDescriptions(params);
} else {
this.props.getDescriptions(params);
}
}
and my action looks like this:
export function getDescriptions(params = { brand: null, category: null, gender: null }) {
return (dispatch) => {
dispatch(requestDescription());
return request
.get(`${getApiUrl()}plp?${QueryString.stringify(params)}`)
.end((err, res) => {
if (err && res.statusCode !== 404) {
...
}
if (res.statusCode === 404) {
// HERE:
console.log(params.gender);
return dispatch(receiveEmptyDescription(params));
}
return dispatch(receiveDescription(res.body));
});
};
}
So up until now, I hadn't noticed the error, but just did when I began testing a scenario where both API calls return a 404.
The error being that having the concurrent calls to the same endpoint is overwriting my params. When the API returns a 200, I could not see the problem. But now when I'm testing returning a 404 I can clearly see the problem.
The problem im getting lies here:
this.props.getDescriptions(params);
params.gender = 'women';
If I check the console log inside my action ( //HERE
) , on both cases params.gender
displays 'women'
even though the first time around its supposed to be 'men'
I guess this can be fixed using a promise?
Let me know if I'm not clear enough.
Upvotes: 2
Views: 2311
Reputation: 35491
The problem isn't really that you're making parallel requests or that you're getting an HTTP2XX or an HTTP4XX.
The reason you are always seeing gender
equal to 'women'
is that you're using the same object instance for both requests, i.e. params
.
What is happening is that you set params.gender
to be 'men'
, fire of the first request, set params.gender
to be 'women'
, fire of the second request.
All the steps above happen synchronously, before any request is completed.
This means that long before any request is finished, params.gender
is already equal to 'women'
.
Just send a different object to each action.
requestDescriptions(params, bothGender) {
if (bothGender) {
// men request
this.props.getDescriptions({ ...params, gender: 'men' });
// women request
this.props.getDescriptions({ ...params, gender: 'women' });
} else {
this.props.getDescriptions(params);
}
}
Since you're already using Redux, you should be aware that mutation is baaaad 😊
Upvotes: 3