Modifying the country drop-down list

We earlier had a country drop-down list that received a list of countries. Let's rewrite it so that if no such list is provided, it will use a function to call a thunk, and get the countries from our server:

// Source file: src/regionsApp/countrySelect.component.js

/* @flow */

import React from "react";
import PropTypes from "prop-types";

import "../general.css";

export class CountrySelect extends React.PureComponent<{
dispatch: ({}) => any
}> {
static propTypes = {
loading: PropTypes.bool.isRequired,
list: PropTypes.arrayOf(PropTypes.object).isRequired,
onSelect: PropTypes.func.isRequired,
getCountries: PropTypes.func.isRequired
};

componentDidMount() {
if (this.props.list.length === 0) {
this.props.getCountries();
}
}

onSelect = (e: { target: HTMLOptionElement }) =>
this.props.onSelect(e.target.value);

render() {
if (this.props.loading) {
return <div className="bordered">Loading countries...</div>;
} else {
const sortedCountries = [...this.props.list].sort(
(a, b) => (a.countryName < b.countryName ? -1 : 1)
);

return (
<div className="bordered">
Country:&nbsp;
<select
onChange={this.onSelect}
onBlur={this.onSelect}
>
<option value="">Select a country:</option>
{sortedCountries.map(x => (
<option
key={x.countryCode}
value={x.countryCode}
>
{x.countryName}
</option>
))}
</select>
</div>
);
}
}
}

As we can see in the .componentDidMount() method, if no list is available, we call a function (which we'll see soon) to get that list, and put it in the store. A loading attribute will be used, so while we wait for the countries to arrive, a Loading countries... text will be shown instead of an empty <select> component. You'll also notice that I sorted the countries, because the service sends them ordered by country code.

The connected version of this component is not as short as before, because we'll have to connect props to the store, and also to actions to be dispatched; I highlighted those parts of the code in the following snippet: 

// Source file: src/regionsApp/countrySelect.connected.js

/* @flow */

import { connect } from "react-redux";

import { CountrySelect } from "./countrySelect.component";
import { getCountries, getRegions } from "./world.actions";

const getProps = state => ({
list: state.countries,
loading: state.loadingCountries
});

const getDispatch = dispatch => ({
getCountries: () => dispatch(getCountries()),
onSelect: c => dispatch(getRegions(c))
});

export const ConnectedCountrySelect = connect(
getProps,
getDispatch
)(CountrySelect);
..................Content has been hidden....................

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