Sunday, February 3, 2019

Redux - 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 store.dispatch().

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.


For e.g.

const ADD_TODO = 'ADD_TODO';

{
   type: ADD_TODO,
   Text: 'Sample data'
}

Other than type, the structure of an action object is really up to the developer.

Action Creators

Action creators are exactly that—functions that create actions
For e.g.

function addTodo(text) {
return {type:ADD_TODO,text}
}

to actually initiate a dispatch, pass the result to the dispatch() function:
dispatch(addTodo(text))

We can also bound action creator that automatically dispatches:

const boundAddTodo = text => dispatch(addTodo(text))
const boundCompleteTodo = index => dispatch(completeTodo(index))

The dispatch() function can be accessed directly from the store as store.dispatch(), but more likely you'll access it using a helper like react-redux's connect(). You can use bindActionCreators() to automatically bind many action creators to a dispatch() function.


References:
https://redux.js.org/basics/actions

1 comment: