- Welcome again and thank you for continuing this journey with me. Today FreeCodeCamp wants us to work with action types. When working with Redux its common practice to assign action types as read-only constants(
const
declarations), then reference these constants wherever they are used. - Code:
const defaultState = {
authenticated: false
};
const authReducer = (state = defaultState, action) => {
switch (action.type) {
case 'LOGIN':
return {
authenticated: true
}
case 'LOGOUT':
return {
authenticated: false
}
default:
return state;
}
};
const store = Redux.createStore(authReducer);
const loginUser = () => {
return {
type: 'LOGIN'
}
};
const logoutUser = () => {
return {
type: 'LOGOUT'
}
};
FreeCodeCamp wants us to declare
LOGIN
andLOGOUT
as const values and assign them to the strings'LOGIN'
and'LOGOUT'
, respectively. Then, edit the authReducer() and the action creators to reference these constants. Remember to write them all uppercase.Answer:
const LOGIN = 'LOGIN'
const LOGOUT = 'LOGOUT'
const defaultState = {
authenticated: false
};
const authReducer = (state = defaultState, action) => {
switch (action.type) {
case LOGIN:
return {
authenticated: true
}
case LOGOUT:
return {
authenticated: false
}
default:
return state;
}
};
const store = Redux.createStore(authReducer);
const loginUser = () => {
return {
type: LOGIN
}
};
const logoutUser = () => {
return {
type: LOGOUT
}
};
Top comments (1)
FWIW, FCC's Redux course is unfortunately outdated (as are many other tutorials online).
It'll help teach you the basics, but "modern Redux" with Redux Toolkit is a lot simpler and easier to learn. In fact, with Redux Toolkit you don't have to write any action types or action creators yourself. RTK's
createSlice
API generates those for you automatically behind the scenes.See our official Redux docs tutorials:
redux.js.org/tutorials/index