I am trying to follow up Brad Travery tutorial of MERN stack. And he uses dispatch function most of the time when working with redux.
Here is userAction.js for instance,
import axios from 'axios'
import { USER_LOGIN_FAIL, USER_LOGIN_REQUEST, USER_LOGIN_SUCCESS } from '../constants/userConstants'
export const login = (email, password) => async (dispatch) => {
try {
dispatch({
type: USER_LOGIN_REQUEST
})
const config = {
headers: {
'Content-Type': 'application/json'
}
}
const { data } = await axios.post('/api/users/login', {email, password}, config)
dispatch({
type: USER_LOGIN_SUCCESS,
payload: data
})
localStorage.setItem('userInfo', JSON.stringify(data))
} catch (error) {
dispatch({
type: USER_LOGIN_FAIL,
payload:
error.response && error.response.data.message ? error.response.data.message : error.message,
})
}
}
dispatch
takes an action and "gives" it to the redux store, which in turn results in the redux store executing the reducers and leading to a change in the store.
That said, that tutorial you are following is teaching a horrible outdated style of Redux. Modern Redux looks very different - please follow the official Redux tutorial instead.