I'm building my first React front end and see a number of conventions for messages sent via the Dispatcher. e.g.
{
type: ActionTypes.RECEIVE_RAW_MESSAGES,
rawMessages: rawMessages
}
and
{
source: 'VIEW_ACTION',
action: action
}
What is the best message format to use & why?
The short answer is, it probably doesn't really matter—as long as your stores look for the right data. I always use the following format:
{
type: 'ACTION_TYPE', // usually defined by a constant
payload: { ... } // a payload of JSON serializable types
}
If your app needs to distinguish between actions that are initiated by the user and actions that come from the server or some other source, you may considering adding a source
key; I personally use separate action types or data within the payload for this purpose.
I always make payload
an object (never a raw value) so that data can be added easily without changing receiving sites. For example, instead of
dispatch({type: ACTION_TYPE, payload: id})
I would recommend
dispatch({type: ACTION_TYPE, payload: {id: id}})
Of course, some of this may be dictated by which flux implementation (if any) that you use. The Facebook dispatcher is very agnostic (you can send pretty much anything you want), but some implementations require specific keys (like type
, etc).