Reputation: 644
I'm having trouble understanding how to rewrite normal action/reducer code to make use of redux-thunk or redux-promise-middleware so I can use promises.
I want to wait for my updatePhone to finish updating my state.user.information.phone
before it starts testUserPhone. So obviously I need a promise to be returned from updatePhone
.
this.props.updatePhone('+1**********')
.then(() => this.props.testUserPhone(this.props.user.information.phone))
action
export const updatePhone = (phone) => ({
type: UPDATE_PHONE,
payload: phone
})
and reducer
export default (state = INITIAL_STATE, action) => {
switch(action.type) {
case 'UPDATE_PHONE':
return {...state,
information: {
...state.information,
phone: action.payload
}
}
default:
return state
}
}
Should I write something like this as well as the basic function, or can I somehow combine them into one? Because I need the action to fully complete its cycle through my reducer and update phone
before it comes back, but I don't want to break my reducer because now it won't be able to access payload
and such since it's inside of a returned function -- super confused with how you start off using these libraries.
export function updatePhoneAsync(phone) {
return dispatch({
type: UPDATE_PHONE,
payload: phone
})
}
EDIT: So I've got this now for my action creators
export const updatePhone = (phone) => ({
type: UPDATE_PHONE,
payload: phone
})
export function updatePhoneAsync(phone) {
return function (dispatch) {
dispatch(updatePhone(phone))
}
}
Outside in my component;
this.props.updatePhoneAsync('+1**********')
.then(() => this.props.testUserPhone(this.props.user.information))
Which gives me an error 'cannot read property then of undefined'
Upvotes: 0
Views: 197
Reputation: 2197
You should write something like this if you use redux-thunk:
Action creators:
function update (params if you need them) {
return function (dispatch) {
send request here
.then(data =>
dispatch(phoneUpdated(data));
}
function phoneUpdated(phone) {
return {type: 'PHONE_UPDATED', phone};
}
Then, feel free to grab this action in your reducer and update the state as you wish.
Also, you can enhance it with additional actions in case when promise will be rejected, or at the start of request to show loader animations
Upvotes: 1