React - How to get data from thunk dispatch in useEffect with useDispatch?

199 Views Asked by At

I have a component where I would like to fetch some data. I have this fetch function:

export const getServicesFromExternalApi =
  (
    customerNumber: string,
    subcustomer: string | null,
    pickupCountryCode: string,
    pickupPostalCode: string,
    deliveryCountryCode?: string,
    deliveryPostalCode?: string
  ) =>
  (dispatch: ThunkDispatch) => {
    const pickupPostalCodeTrimmed = validTrimmed(pickupPostalCode) ? replace(pickupPostalCode, ' ', '') : null
    const deliveryPostalCodeTrimmed =
      deliveryPostalCode && validTrimmed(deliveryPostalCode) ? replace(deliveryPostalCode, ' ', '') : null

    const servicesUrl = `/api/external/services?customerNo=${
      customerNumber || ''
    }&subcustomer=${subcustomer || ''}&pickupCountryCode=${pickupCountryCode || ''}&pickupPostalCode=${
      pickupPostalCodeTrimmed || ''
    }&deliveryCountryCode=${deliveryCountryCode || ''}&deliveryPostalCode=${deliveryPostalCodeTrimmed || ''}`
    return dispatch(
      asyncRequest(
        fetch(servicesUrl, {
          method: 'GET',
          credentials: 'include',
        }),
        GET_SERVICES
      )
    )
  }

And this is how I use it in my component:

const dispatch = useDispatch()

  useEffect(() => {
    const consignment = props.shipment.get('consignments').first()
    const serviceParams = {
        customerNumber: props.shipment.get('custNr'),
        subcustomer: props.shipment.get('custSubcustomer') || '',
        pickupCountryCode: props.shipment.get('pickupCountry'),
        pickupPostalCode: props.shipment.get('pickupZipCode').trim(),
    }
    const services = dispatch(getServicesFromExternalApi(
      serviceParams.customerNumber,
      serviceParams.subcustomer,
      serviceParams.pickupCountryCode,
      serviceParams.pickupPostalCode
    ))
    console.log(services)

When I log this I get Promise<pending>. How can I get result data from that call?

1

There are 1 best solutions below

0
Gabor Szabo On

I have this custom hook in hooks.ts by thi Redux typescript

import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from './store';

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;`

In the component you should import:

const services = useAppSelector((state) => state.services.fetchedServices);

And simply use the services.