Using thunks

Now, things start getting interesting. We are providing two functions to the country drop-down list, both of which will work with thunks in order to connect to the server. Let's see them!

We'll need two functions: one will deal with getting the list of countries, and the other will be used to get the regions for the currently selected country. Let's just begin with the former, and keep in mind that this code is to be added to the action file we saw earlier:

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

import axios from "axios";

export const getCountries = () => async dispatch => {
try {
dispatch(countriesRequest());
const result = await axios.get(`http://fk-server:8080/countries`);
dispatch(countriesSuccess(result.data));
} catch (e) {
        dispatch(countriesFailure());
}
};

First, the signature for our getCountries() function is a bit weird (a function that returns an async function, with a dispatch parameter), but this is what redux-thunk requires. The logic is more interesting:

  • To start, we dispatch the results of the countriesRequest() action creator, so the state of the application will show that we are waiting for some results.
  • Then, we use the axios() package, as used earlier in our Node work, to call our server and get the list of countries.
  • If the call is successful, we dispatch a countriesSuccess() action, passing it the list of countries that we received.
  • If the call failed, we dispatch a countriesFailure() action, to show that failure.

As you can see, our code is able to dispatch many actions, but waiting until the right moment to do so. 

To work with regions, we'll have similar code:

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

export const getRegions = (country: string) => async dispatch => {
if (country) {
try {
dispatch(regionsRequest());
const result = await axios.get(
`http://fk-server:8080/regions/${country}`
);
dispatch(regionsSuccess(result.data));
} catch (e) {
dispatch(regionsFailure());
}
} else {
dispatch(regionsFailure());
}
};

The code is quite similar to what we had before, so we don't need to do much analysis. 

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

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