-
Notifications
You must be signed in to change notification settings - Fork 7
Getting started with Redux and AskAGator
We use Redux to manage state in our project. We also use React Hooks to make creating components and state easy. Well we can combine these two to make development a lot quicker than before.
Redux is broken up into Actions, Reducers, and the Store. These combine to pass context throughout our application.
Actions can do whatever we want. They are just functions that return an Dictionary with the action type and the data.
For example, the loginAct takes a User and just returns it back with a type.
export function loginAct(user: IUser) {
return {
type: AUTH_ACTIONS.LOGIN_ACT,
user,
};
}
On the other hand you don't even need data:
export function logoutAct() {
return {
type: AUTH_ACTIONS.LOGOUT_ACT,
};
}
Then we pass these actions to the dispatcher.
The reducers take our old state, the action you just sent to the dispatcher and return the new state. This function is pure meaning that if we send the same input in we should get the same output every time.
Here is the auth reducer. As you can see we set the default value of the state to an empty array. Then we switch on that type field that each action has. Finally we return the new state.
const auth = (state = [], action : any) => {
switch (action.type) {
case AUTH_ACTIONS.LOGIN_ACT:
return action.user;
case AUTH_ACTIONS.LOGOUT_ACT:
return { exists: false }
case AUTH_ACTIONS.EDIT_NAME_ACT:
return Object.assign({}, state, {
firstName: action.firstName,
lastName: action.lastName
})
default:
return state
}
};
export default auth;
Using redux with Hooks is super simple. To grab a value from the state you call the function useSelector which takes a function, which takes the state and returns the value you want. For example if we want to return the auth from state.auth we do this:
const auth = useSelector((state: any) => ({ ...state.auth }));
Now for dispatching an action all we do is get the dispatcher with:
const dispatch = useDispatch();
And then call our action on it:
dispatch(loginAct({
email,
exists: true,
firstName: "",
lastName: "",
}));