Search code examples
react-reduxredux-toolkitrtk-query

How to use RTK Query in createSlice?


I want to process the data that I get from the request in the slice.

Because not all slices are async (but work with the same data), transformResponse is not suitable.

Is there anything you can suggest?

My code example:

  1. Some RTK Query
export const currencyApi = createApi({
  reducerPath: 'currencyApi',
  baseQuery: fetchBaseQuery({ baseUrl: 'https://api.apilayer.com/exchangerates_data' }),
  endpoints: (build) => ({
    fetchCurrencyRates: build.query<IApiResponse, string>({
      query: (currency) => ({
        url: '/latest',
        params: {
          base: currency
        },
        headers: {
          apikey: *SomeApiKey*
        }
      })
    })
  })
})
  1. Slice where I want to use data from RTK requests
const initialState: ICurrencyState = {
  currencyRates: {},
  availableCurrencyOptions: [],
  fromCurrency: '',
  toCurrency: '',
  exchangeRate: 0,
  error: null
}

export const currencySlice = createSlice({
  name: 'currency',
  initialState,
  reducers: {
    // 
  }
})

Solution

  • Use Hooks in Components

    You can send the received data to the slice via useEffect. Something like this:

    const { data } = useFetchCurrencyRatesQuery();
    
    useEffect(() => {
        if (data !== undefined) {
            dispatch(...)
        }
    }, [data])