⊗jsrxPmATCDT 47 of 57 menu

Dispatching a thunk from a component in Redux

In this lesson we'll dispatch a thunk to fetch products from the ProductsList React component.

Let's now open our product app, and in it the file ProductsList.jsx. First, let's add to the import the thunk fetchProducts that we created:

import { selectAllProducts, fetchProducts } from './productsSlice'

We'll also need the useDispatch hook to dispatch our action creator and the useEffect hook because we have a side effect here, since we're dealing with the grid, which is an external API:

import { useEffect } from 'react' import { useSelector, useDispatch } from 'react-redux'

Now, as the first line in the code of the ProductsList function, before the declaration of products, we add:

const dispatch = useDispatch()

Next, when receiving products from the state, we will also extract the request status:

const products = useSelector(selectAllProducts) const productStatus = useSelector((state) => state.products.status)

And right after that, we tell React using the useEffect hook that we need to get the products after rendering the component. This is where we need the request status, because it is important for us that such a request is sent only once:

useEffect(() => { if (productStatus === 'idle') { dispatch(fetchProducts()) } }, [productStatus, dispatch])

Now we can run our application, click on 'Products' in the menu on the left. We won't see the list of products yet, but if we go to our Redux DevTools, then in the left part of the window we will see automatically generated (as I said in the last lesson) actions products/fetchProducts/pending and fulfilled. Now let's click on the action products/fetchProducts/fulfilled and on its field payload - here is our list of products! Hooray, all our links in the chain - the server, the database, the client and Redux - the application work harmoniously and together. By the way, as you can see, there is also a property meta, in which we see the request status.

One more thing to note, you may have pending and therefore fulfilled appearing twice. If so, don't worry, we'll talk about that later.

Open your app with students. Open the file StudentsList.jsx in it. Import the necessary hooks and thunk into it according to the material from the lesson.

After reviewing the lesson materials, get the request status studentStatus, then use useEffect to send fetchStudents only if the value of studentStatus is 'idle'.

Run your app, click on 'Students' in the app menu on the left, and then run the Redux DevTools extension in the browser, as in this tutorial you should see actions with pending and fulfilled (and in it payload with students). Explore the extension tabs.

enru