Ghasem Khalili
Ghasem Khalili

Reputation: 973

How can I wait until I get the dispatch result in React

consider the following code :

const onSubmit = (data) => {
    dispatch(Actions.updatedUser(data))
    navigation.navigate('xxxx')
}

When I call Submit function we want to wait until finishing dispatch then navigate , Here How can I do that ?

This is my action :

export const updatedUser = (model) => {
    return dispatch => {
        api
            .patch("/xxx")
            .then(response => { return response.data['data'] })
            .then(result => {
                dispatch({ type: Actions.AUTH_UPDATE_USER, payload: result })
            })
            .catch(error => { })
    }
}

my reducer :

const initState = {
    userInfo: undefined
}

export default (state = initState, action) => {
    switch (action.type) {
        case Actions.AUTH_UPDATE_USER:
            return { ...state, userInfo: action.payload }
        default:
            return state;
    }
}

Upvotes: 0

Views: 1043

Answers (1)

tanmay
tanmay

Reputation: 7911

Here's what you can do: from your action, you can return a promise which resolves only when the dispatch is completed. Something like this:

export const updatedUser = (model) => {
    return dispatch => {
        return new Promise((resolve, reject) => {
            api
                .patch("/xxx")
                .then(response => { return response.data['data'] })
                .then(result => {
                    dispatch({ type: Actions.AUTH_UPDATE_USER, payload: result })
                    resolve() // <<<< this!
                })
                .catch(error => { reject() })
        })
    }
}

Now, in your component code, you can either do .then or async/await based on your preference. Here's how it would look with then:

const onSubmit = (data) => {
    dispatch(Actions.updatedUser(data)).then(() => {
        navigation.navigate('xxxx')
    })
}

Here's a sandbox for an example

Upvotes: 1

Related Questions