Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Modifying State by Dispatching Actions | Redux in Practice
Introduction to Redux
course content

Contenido del Curso

Introduction to Redux

Introduction to Redux

1. Getting Started
2. Fundamental Concepts
3. Redux in Practice
4. Creating a React-Redux Application

bookModifying State by Dispatching Actions

We learned how to access data from the application state, now we want to make changes. For modifying the application state, we dispatch actions.

Recall that the createSlice function automatically generates the action creators. Currently, our todoSlice file looks like this:

We will use the addTodo action creator in index.js to add new items to the Todo list. Currently, the index.js file looks like this:

We will import addTodo from todosSlice, useDispatch from react-redux, and useState from react.

useDispatch will allow us to dispatch actions, while useState is for creating local states which we don’t want to store in the global application state.

Out imports should now look like this:

We will create a local state variable called text, representing the user's input along with two functions, one for handling the input and one for handling the submission. The code in index.js should now look like this:

The application will look something like this:

However, the Add button will have no effect since we have yet to write code. Note that the handleSubmit function is pretty much empty.

We will declare a new constant in the App component and assign a useDispatch call to it:

We will then use this const function to dispatch the addTodo function in the handleSubmit function, passing the argument text in it. We will also clear the text afterward:

Note that we can pass extra data with the action by passing an argument to the action creator. In this case, we directly passed a string text. For more data, we can pass an object containing key-value pairs and access it using the payload from todosSlice. The final code will look like this:

Now we should be able to add new items to the Todo list:

How can we send additional data with dispatched actions?

How can we send additional data with dispatched actions?

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 8
some-alt