Redux-Thunk: A better way to fetch data
Explore how to use redux-thunk middleware to perform asynchronous data fetching within Redux actions. This lesson helps you understand how to separate concerns by moving data requests outside components, making your React app easier to manage and extend.
We'll cover the following...
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 body = ...