Creating actions

In this section, we are going to create actions that will initiate changes to our store state. Let's get started:

  1. We are going to create the actions in Store.ts. So, let's add the following import statement at the top of this file:
import { Action } from 'redux';

The Action type is a base type from the core Redux library that contains a type property that we can use to type in our actions.

  1. Let's create an action interface that will indicate that unanswered questions are being fetched from the server:
interface GettingUnansweredQuestionsAction
extends Action<'GettingUnansweredQuestions'> {}

Notice that the interface uses the extends keyword.

Interfaces can inherit properties and methods from another interface using the extends keyword. The interface that's being inherited from is specified after the extends keyword.

We have extended the generic Action type by passing in the type for the type property, which is the 'GettingUnansweredQuestions' string literal.

The action has no other properties, so the object will always be as follows:

{
type: 'GettingUnansweredQuestions'
}

The type property can only be 'GettingUnansweredQuestions' and no other string value because we have typed it to that specific string literal.

  1. Let's create an action for when the unanswered questions have been retrieved from the server:
export interface GotUnansweredQuestionsAction
extends Action<'GotUnansweredQuestions'> {
questions: QuestionData[];
}

This time, the action contains a property called questions to hold the unanswered questions, as well as the fixed type property.

  1. Our last action is for when a question has been posted to the server and we have the response:
export interface PostedQuestionAction extends Action<'PostedQuestion'> {
result: QuestionData | undefined;
}

The result property will hold the result of the question submission.

  1. Now, we are going to combine all the action types in a union type:
type QuestionsActions =
| GettingUnansweredQuestionsAction
| GotUnansweredQuestionsAction
| PostedQuestionAction;

We'll use this union type later in this chapter when we implement the reducer.

That's our actions defined. In the next section, we'll create functions that will dispatch these actions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.148.113.111