React-Redux: Fixed Action Types
Intro
One way to prevent type errors while using React-Redux is to create a validation list for action types, also known as fixed action types, so that we can be sure we don't make any typos while assigning types to actions and reducers.
Action Types File
We can start by making a new file in the actions directory called types, and in this file we just assign variables to the type strings.
export const SIGN_IN = 'SIGN_IN';
export const SIGN_OUT = 'SIGN_OUT';
The benefit here is that if we try to reference one of these variables later, if we mistype it we will get a warning that the reference is undefined.
Using Action Variables
To use the action type variables that we have created we simply have to import them and replace the strings with their equivalent variables.
import { SIGN_IN, SIGN_OUT } from './types' // highlight-line
export const signIn = () => {
return {
type: SIGN_IN, // highlight-line
};
};
export const signOut = () => {
return {
type: SIGN_OUT, // highlight-line
};
};
import { SIGN_IN, SIGN_OUT } from '../actions/types' // highlight-line
const INITIAL_STATE = {
isSignedIn: null
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case SIGN_IN: // highlight-line
return {...state, isSignedIn: true };
case SIGN_OUT: // highlight-line
return {...state, isSignedIn: false };
default:
return state;
}
};
Comments
Recent Work
Basalt
basalt.softwareFree desktop AI Chat client, designed for developers and businesses. Unlocks advanced model settings only available in the API. Includes quality of life features like custom syntax highlighting.
BidBear
bidbear.ioBidbear is a report automation tool. It downloads Amazon Seller and Advertising reports, daily, to a private database. It then merges and formats the data into beautiful, on demand, exportable performance reports.