How to dispatch in .then() in react-redux

Viewed 2217

I am working on project where I am stuck in this problem. The thing is, I am calling an axios API and after its success I want to update my redux state i.e. in the .then() chain of axios. How can I achieve that? As what I have tried by applying what I know is -> I have created a react-redux dispatch in my component. I know how to do this in normal onClick but in then method I don't know how to trigger that.

I have tried doing this:

 let submitForm = (e) => {
        e.preventDefault();

        // Axios request 
        const url = 'http://localhost:5000/api/v1/users/login'
        axios({
           //Api details 
        })
            .then(res => {
              // Store API data in LocalStorage
            })
            .then(() => {
                LogIN(); // Here I want to change redux state //
                
                history.push('/dashboard')
            })
 
    }


--Component 
function Signin({LogIN}) {
    return (
    )

}


const mapDispatchToProps = dispatch => {
    return {
        LogIN: () => dispatch(login_action())
    }
}
export default connect(null , mapDispatchToProps)(Signin)


After doing this, I see same state with no difference

Here is redux:

const login_action = () => {
    return {
        type : 'LOG-IN'
    }
}

const loginLogOutReducer = (state = false, action) => {
    switch (action.type) {
        case 'LOG_IN':
            return !state
        default:
            return state
    }
}


const AllReducers = combineReducers({
    isLoggedIn : loginLogOutReducer
})
1 Answers

You can use redux-thunk and function component in react hook

App.js

import {Provider} from 'react-redux'
import store from './store'

<Provider store={store()}>
    <AppComponent />
</Provider>

store.js

import {applyMiddleware, compose, createStore} from 'redux'
import thunk from 'redux-thunk'
import {initialState, rootReducer} from './reducers'

const store = () => {
    return createStore(rootReducer, initialState, compose(applyMiddleware(thunk)))
}

export default store

reducer.js

import {actionTypes} from './actionTypes'

const initialState = {}

const rootReducer = (state = initialState, action) => {
    if (action.type === actionTypes.STH) {
        return {
            ...state,
            sth: action.payload,
        }
    }
}

export {initialState, rootReducer}

actionTypes.js

export const actionTypes = {
    STH: 'STH'
}

Component

...
const onChange =  => {
    dispatch(actionFunc()).then(res => {
        // DO Something
    })
...

action.js

const actionFunc = () => {
    return (dispatch, getState) => {
        return axios({
           //Api details 
        }).then(res => res).catch(err => err)
    }
}
Related