Constants
Within a Flux app, Constants are used to represent the actions that should be carried out or responded to.
We need to create a constant to represent our search Github action. We actually already used these in src/reducers/user.js
before we've created them. Create a folder constants
in src
and create a new file User.js
:
import { createConstants } from 'gambit';
export default createConstants([
'GET_USER_SEARCH',
]);
Pretty simple and bland eh? Well createConstants is actually doing something interesting:
DONE, STARTING, FAILED
createConstants
actually returns four constants for every entry in the array you pass it:
createConstants(['FOO']) => ['FOO_DONE', 'FOO_STARTING', 'FOO_FAILED', 'FOO'];
You may only ever user FOO
or FOO_DONE
in a simple app but the Gambit action creators will fire them all at varying points:
GET_USER_SEARCH_STARTING
will be fired when the action creator receives the request to call an API.GET_USER_SEARCH_DONE
will be fired when the action creator receives a 200 responseGET_USER_SEARCH_FAILED
will be fired when the action creator receives a non-200 response
This makes it easy to create reducers that monitor the state of a certain API call, making it easy to create UIs that show the correct loading screens and error information.
Always use the variable
You may be tempted, if you've created some simple constants, to just use a string comparison in a reducer. Don't. You should always reference an action by using the variable (FOO_DONE
rather than 'FOO_DONE'
). This is because Gambit actually changes the output of the createConstants
constants so that +
in reducers will work, this means that:
const Constants = createConstants(['FOO']);
Constants.FOO === 'FOO' // false
Constants.FOO === Constants.FOO // true