Most well-designed applications will have separate components that need to communicate and share data with each other.
A todo list might have an input field where the user can type in a new todo item. The application might transfer this data from the input field, add it to an array of all todos, and then render them as text on the screen. This entire interaction can be defined as an action. In Redux, actions are represented as plain JS objects.
Here’s what that action might look like:
const action = { type: 'todos/addTodo', payload: 'Take selfies' };
- Every action must have a
type
property with a string value. This describes the action. - Typically, an action has a
payload
property with an object value. This includes any information related to the action. In this case, the payload is the todo text. - When an action is generated and notifies other parts of the application, we say that the action is dispatched.
Here are two more example actions:
“Remove all todos”. This requires no payload
because no additional information is needed:
const action = { type: 'todos/removeAll' }
“Remove the ‘Pack snacks’ todo”:
const action = { type: 'todos/removeTodo', payload: 'Pack snacks' }
Instructions
Define an action object named addNewSong
that represents adding a new song to the playlist.
It should have the following information:
- A
type
of'songs/addSong'
- A
payload
of'Halo'
, the title of the song to add
Define an action named removeSong
that represents removing a song from the playlist.
It should have the following information:
- A
type
of'songs/removeSong'
- A
payload
of'Take Five'
, the title of the song to remove
Define an action named removeAll
that represents removing all songs from the playlist.
It should have the following information:
- A
type
of'songs/removeAll'