Creating a demo with Redux and asynchronous

Now the time has come to test everything out. What we are interested in here is ensuring that our store state behaves the way we want it to. We want the store to reflect the fact that we are loading the data, receiving the data, and if there is an error, that should be reflected as well. Let's start out by mimicking an AJAX call:

const { fetchBookLoading, fetchBookSuccess, fetchBookError } = require('./book-actions');
const { dispatch, getState } = require('./redux');

function fetchBook() {
return new Promise(resolve => {
setTimeout(() => {
resolve({ title: 'A new hope - the book' });
}, 1000);
})
}

As our next order of business, let's set up some logging for the state and dispatch our first action, fetchBookLoading, which indicates that an AJAX request is underway. This is where, ideally, we would want to reflect this state in the UI and show a spinner or similar:

console.log(getState());
// { book: {} }

dispatch(fetchBookLoading());

console.log(getState());
// { book: { loading: true } }

The last step is about a call to our fetchBook() method and setting the store state appropriately:

async function main() {
try {
const book = await fetchBook();
dispatch(fetchBookSuccess(book));
console.log(getState());

// { book: { data: { title: 'A new hope - the book'}, loading: false } }
} catch(err) {
dispatch(fetchBookError(err));
console.log(getState());

  // { book: { data: undefined, error: { title: 'some error message' } } }
}
}

main();

We have so far described our demo in pieces from top to bottom. The full code should read like this:

// async/demo.js

const { fetchBookLoading, fetchBookSuccess, fetchBookError } = require('./book-actions');
const { dispatch, getState } = require('./redux');

function fetchBook() {
return new Promise(resolve => {
setTimeout(() => {
resolve({ title: 'A new hope - the book' });
}, 1000);
})
}

console.log(getState());
dispatch(fetchBookLoading());
console.log(getState());

async function main() {
try {
const book = await fetchBook();
dispatch(fetchBookSuccess(book));
console.log(getState());
} catch(err) {
dispatch(fetchBookError(err));
console.log(getState());
}
}

main();

As you can see, there is really not much to dealing with asynchronous, you just need to dispatch the suitable state once the asynchronous action has run its course. There are libraries for dealing with asynchronous though. If you are a React user it might be worth looking into Sagas and if Angular is your flavor, then NgRx and effects is your go-to. The reason for separate libraries existing for this is to say that asynchronous interactions, especially AJAX ones, are considered side-effects and as such they are outside the normal flow. Ultimately, it's up to you if you feel you need such a library.

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

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