Defining the actions

Whenever you try to get data from a service, a common pattern is as follows:

  • Fire an action when you do the request; this action may set some flag, which will in turn be used by some component to display a "Loading..." text or a spinning icon to show that something's going on, and the user should wait
  • If the service request was successful, fire an action signaling this success, resetting the Loading... flag, and also providing the new data that must be added to the store
  • If the service request failed, reset the Loading... flag, but signal error in some way

The actions we'll need for our application have to do with, firstly, getting the list of countries for the country drop-down list, and, secondly, getting the list of regions for a given country. The actions are as follows; first, here are the country-related ones:

// Source file: src/regionsApp/world.actions.js

/* @flow */

// Countries actions

export const COUNTRIES_REQUEST = "countries:request";
export const COUNTRIES_SUCCESS = "countries:success";
export const COUNTRIES_FAILURE = "countries:failure";

export type CountriesAction = {
type: string,
country?: string,
listOfCountries?: [object]
};

export const countriesRequest = () =>
({
type: COUNTRIES_REQUEST
}: CountriesActions);

export const countriesSuccess = (listOfCountries: []) =>
({
type: COUNTRIES_SUCCESS,
listOfCountries
}: CountriesActions);

export const countriesFailure = () =>
({
type: COUNTRIES_FAILURE
}: CountriesActions);


// continues...

For regions, we have a similar set:

// ...continued

// Regions actions

export const REGIONS_REQUEST = "regions:request";
export const REGIONS_SUCCESS = "regions:success";
export const REGIONS_FAILURE = "regions:failure";

export type RegionsAction = {
type: string,
listOfRegions?: [object]
};

export const regionsRequest = (country: string) =>
({
type: REGIONS_REQUEST,
country
}: RegionsActions);

export const regionsSuccess = (listOfRegions: [{}]) =>
({
type: REGIONS_SUCCESS,
listOfRegions
}: RegionsActions);

export const regionsFailure = () =>
({
type: REGIONS_FAILURE
}: RegionsActions);

Note the style of the action constants—we are using "countries" and "regions" as a sort of namespacing (as in "countries:success" versus "regions:success") to avoid possible name duplications. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.141.6