...
/Redux-Thunk: A better way to fetch data
Redux-Thunk: A better way to fetch data
Fetching data is Redux apps can be streamlined by using redux-thunk. We are going to use redux-thunk to fetch weather data
We'll cover the following...
The idea behind redux-thunk
is that we return a function from an action that gets passed dispatch
. This allows us to do asynchronous things (like data fetching) in our actions:
function someAction()
// Notice how we return a function – this is what's called a "thunk"!
return function thisIsAThunk(dispatch) {
// Do something asynchronous in here
}
}
First implementation
Let’s try to write an action called fetchData
that fetches our data! Start with the basic structure:
// actions.js
/* …more actions here… */
export function fetchData() {
return function thunk(dispatch) {
// LET'S FETCH OUR DATA HERE
}
}
Now let’s copy and paste the xhr
call from the App
component and put it in there:
// actions.js
/* …more actions here… */
export function fetchData() {
return function thunk(dispatch) {
xhr({
url: url
}, function (err, data) {
var
...