Actions
Last updated
Was this helpful?
Last updated
Was this helpful?
First, let's define some actions.
Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using .
Here's an example action which represents adding a new todo item:
Actions are plain JavaScript objects. Actions must have a type
property that indicates the type of action being performed. Types should typically be defined as string constants. Once your app is large enough, you may want to move them into a separate module.
Note on Boilerplate
You don't have to define action type constants in a separate file, or even to define them at all. For a small project, it might be easier to just use string literals for action types. However, there are some benefits to explicitly declaring constants in larger codebases. Read for more practical tips on keeping your codebase clean.
Other than type
, the structure of an action object is really up to you. If you're interested, check out for recommendations on how actions could be constructed.
We'll add one more action type to describe a user ticking off a todo as completed. We refer to a particular todo by index
because we store them in an array. In a real app, it is wiser to generate a unique ID every time something new is created.
It's a good idea to pass as little data in each action as possible. For example, it's better to pass index
than the whole todo object.
Finally, we'll add one more action type for changing the currently visible todos.
Action creators are exactly that—functions that create actions. It's easy to conflate the terms “action” and “action creator,” so do your best to use the proper term.
In Redux action creators simply return an action:
This makes them portable and easy to test.
In Redux this is not the case.
Instead, to actually initiate a dispatch, pass the result to the dispatch()
function:
Alternatively, you can create a bound action creator that automatically dispatches:
Now you'll be able to call them directly:
actions.js
In , action creators often trigger a dispatch when invoked, like so:
The dispatch()
function can be accessed directly from the store as , but more likely you'll access it using a helper like 's connect()
. You can use to automatically bind many action creators to a dispatch()
function.
Action creators can also be asynchronous and have side-effects. You can read about in the to learn how to handle AJAX responses and compose action creators into async control flow. Don't skip ahead to async actions until you've completed the basics tutorial, as it covers other important concepts that are prerequisite for the advanced tutorial and async actions.
Now let's to specify how the state updates when you dispatch these actions!