In my React app I'm trying to fake a delay in mock API response
Uncaught TypeError: Cannot read property 'then' of undefined
createDraft() {
// Post to Mock API
const newDraft = {
name: this.state.draftName,
created_by: this.props.user,
created: getDate()
};
/* ERROR HERE */
this.props.create(newDraft).then((res) => {
console.log(' res', res);
// Display loading spinner while waiting on Promise
// Close modal and redirect to Draft Summary view
this.props.closeModal();
});
}
The action:
export const create = newDraft => dispatch => all()
.then(() => setTimeout(() => {
dispatch({
type: CREATE,
newDraft
});
return 'Draft created!';
}, 2000))
.catch(() => {
dispatch({
type: REQUEST_ERROR,
payload: apiErrors.BAD_REQUEST
});
});
Connected area:
const mapDispatchToProps = dispatch => ({
create: (newDraft) => { dispatch(create(newDraft)); }
});
export const CreateDraftModalJest = CreateDraftModal;
export default connect(cleanMapStateToProps([
'user'
]), mapDispatchToProps)(CreateDraftModal);
function DelayPromise(t) {
return new Promise(((resolve) => {
setTimeout(resolve, t);
}));
}
export const create = newDraft => dispatch => all()
.then(DelayPromise(2000))
.then(() => {
console.log('created called', newDraft);
dispatch({
type: CREATE,
newDraft
});
})
.then(() => 'Draft created!')
.catch(() => {
dispatch({
type: REQUEST_ERROR,
payload: apiErrors.BAD_REQUEST
});
});
It's possible that your this.props.create()
action creator is not bound to dispatch, and therefore not returning the promise as expected.
Are you using react-redux
connect() properly?
EDIT:
Your mapDispatchToProps is not returning the promise. Do this instead:
const mapDispatchToProps = dispatch => ({
create: (newDraft) => dispatch(create(newDraft)),
});