[Solved] Redux createStore() is deprecated - Cannot get state from getState() in Redux action
Problem:
I am converting my state management from context API to redux. But when I try to use createStore() it says Redux createStore() is deprecated - Cannot get state from getState() in Redux action. Here is my code:
STORE:
import thunk from 'redux-thunk'
import {
userLoginReducer,
userRegisterReducer,
userDeleteReducer,
userUpdateReducer,
} from './reducers/userReducers'
const reducer = {
userLogin: userLoginReducer,
userRegister: userRegisterReducer,
userDelete: userDeleteReducer,
userUpdate: userUpdateReducer,
}
const userInfoFromStorage = localStorage.getItem('userInfo')
? JSON.parse(localStorage.getItem('userInfo'))
: null
const preLoadedState = {
userLogin: { userInfo: userInfoFromStorage },
}
const middleware = [thunk]
const store = configureStore({
reducer,
preLoadedState,
middleware,
})
export default store
ACTION:
import axios from 'axios'
import {
PRODUCT_ADD_FAIL,
PRODUCT_ADD_REQUEST,
PRODUCT_ADD_SUCCESS,
} from '../constants/productConstants'
export const addProduct = product => async (dispatch, getState) => {
try {
dispatch({ type: PRODUCT_ADD_REQUEST })
const {
userLogin: { userInfo },
} = getState()
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${userInfo.token}`,
},
}
const { data } = await axios.post('/product', product, config)
dispatch({
type: PRODUCT_ADD_SUCCESS,
payload: data,
})
} catch (error) {
dispatch({
type: PRODUCT_ADD_FAIL,
payload:
error.message && error.response.data.message
? error.response.data.message
: error.message,
})
}
}
So in this article, we are going to learn how to solve this problem.
Solution:
The createStore is deprecated. You are creating a redux store using vanilla Redux. This pattern is much harder to use. That's why the creator of redux wants us to use Redux Toolkit. You can create store using Redux toolkit very easily. From Redux Toolkit you can use configureStore which wraps around createStore API and handle the store setup automatically. You can read more about it here.
Hope this article solves your problem. If you have any feedback you can comment below