I recently started looking at redux thunks. It is my understanding it should be used for dealing with async actions or where there's a need to dispatch actions from within other actions. So I've got my store configured such as:
import {applyMiddleware, createStore} from "redux";
import rootReducer from "./rootReducer";
import thunk from "redux-thunk";
import { composeWithDevTools } from 'redux-devtools-extension'; // used by redux-devtools to visualize redux in browser
const store = createStore(rootReducer, composeWithDevTools(
applyMiddleware(thunk),
// other store enhancers if any
));
export default store;
My reducer looks like:
const INITIAL_STATE = {
user: null,
}
export const authReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case actionTypes.REGISTER_NEW_USER:
const newUser = action.payload
return {
...state,
'user': newUser
}
default:
return state;
}
}
my thunk is the following (notice I commented out the part that makes an async call for simplicity while I just test the functionality of my thunk):
// Thunks
export const registerUser = (userData) => {
console.log("HERE")
return async (dispatch) => {
let user = new User();
try {
let newUserData;
console.log(userData)
// newUserData = await user.register(userData);
newUserData = {
'email': '[email protected]',
'token': '234jk23hjkhaSDASD',
}
console.log("here in thunk")
console.log(newUserData)
cookie.set("user", newUserData.email);
cookie.set("token", newUserData.token);
// dispatch(createNewUser(newUserData));
dispatch({
type: actionTypes.REGISTER_NEW_USER,
payload: newUserData
})
} catch(e) {
console.log(e);
}
}
}
and my component:
const dispatch = useDispatch();
const onSubmit = data => {
dispatch(registerUser(data));
}
I've written some tests for these but when executing them, they don't seem to be running the thunk function. The console.log("HERE")
statement in registerUser
is executed but none of the logs from within the return method are. What am I missing?
Side question and not as important as the previous one: Now that i'm using Thunks, do all my actions need to be a thunk? or is it ok to have a combination of thunks and actions that are always plain js objects where no async processing is required?
Thanks
It works fine for me.
Execution result:
The doc Writing Logic with Thunks is clear:
You are right, it's ok to have a combination of thunks and actions that are always plain js objects. The plain js object actions are often used for UI actions.
But a better way is to use action creators to create a Flux Standard Actions