Using Asynchronous Calls in Redux
In this lesson, we'd be using asynchronous calls in redux
Using asynchronous calls in Redux#
If you notice, there is some code which we are repeating, for example, the addToCart function. The functionality is exactly the same, but we still use the same code at different locations. Our Redux toolkit gives us a way to use asynchronous calls from Redux. So let's see how to do it.
We will start with the basketSlice. We can also handle the loading from here, so let's create a new piece of state inside our basket and let's call it status, and this will be of type string. We can also mention the initial state to be idle. Now let's create our asynchronous function, and export const addBasketItemAsync which will be equal to the createAsyncThunk which is provided by redux-toolkit.
The first thing we need to pass is the type prefix. You can write as the basket name then slash then the name of the function, so let's write basket/addBasketItemAsync. Now, we will write our payload creator, async and in the parameters, we will pass what we need to pass in the async call. In our case, we just need to add the course id, so let's do that. Since we're using async keyword, let's use our try catch block inside. Inside our catch block, we will have access to the error block and we can log it for now. We see the error because our createAsyncThunk does not have any. If we hover over it, it has void void and an empty object.