create an reducer in typescript

To create a Redux reducer in TypeScript, you can follow the steps below:

  1. Define an interface for the state of your application. This is the shape of the data that your reducer will manage.
index.ts
interface AppState {
  data: any[];
  loading: boolean;
  error: string | null;
}
82 chars
6 lines
  1. Define an initial state for your application. This will be used as the default value when the reducer is first called.
index.ts
const initialState: AppState = {
  data: [],
  loading: false,
  error: null
};
80 chars
6 lines
  1. Define your reducer function. The reducer function takes the current state and an action object as arguments and returns the new state of the application.
index.ts
const reducer = (state: AppState = initialState, action: any) => {
  switch (action.type) {
    case "FETCH_DATA_REQUEST":
      return {
        ...state,
        loading: true,
        error: null
      };
    case "FETCH_DATA_SUCCESS":
      return {
        ...state,
        data: action.payload,
        loading: false,
        error: null
      };
    case "FETCH_DATA_FAILURE":
      return {
        ...state,
        loading: false,
        error: action.payload
      };
    default:
      return state;
  }
};
522 chars
26 lines

In the above code, we have defined a reducer function that updates the state based on the action type. In each case, we use the spread operator to create a new state object with the changes we want to make.

  1. Export your reducer function so it can be used by your Redux store.
index.ts
export default reducer;
24 chars
2 lines

That's it! With these steps, you can create a Redux reducer in TypeScript that manages the state of your application.

gistlibby LogSnag