Trouble fetching data from RapidAPI in Redux setup

I’m having issues getting data from RapidAPI using Redux. When I log the data, I get a 401 Unauthorized error. Can someone help me figure out what’s wrong?

Here’s my store.js file:

import { configureStore } from '@reduxjs/toolkit'
import { coinDataApi } from '../services/coinDataApi'

const store = configureStore({
  reducer: {
    [coinDataApi.reducerPath]: coinDataApi.reducer,
  },
})

export default store

And here’s where I set up the API call:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

const coinApiHeaders = {
  'X-RapidAPI-Host': 'cryptocurrencyranking.p.rapidapi.com',
  'X-RapidAPI-Key': 'your-api-key-here'
}

const apiUrl = 'https://cryptocurrencyranking.p.rapidapi.com/currencies'
const prepareRequest = (url) => ({ url, headers: coinApiHeaders })

export const coinDataApi = createApi({
  reducerPath: 'coinDataApi',
  baseQuery: fetchBaseQuery({ baseUrl: apiUrl }),
  endpoints: (builder) => ({
    getCurrencies: builder.query({
      query: () => prepareRequest('/list')
    })
  })
})

export const { useGetCurrenciesQuery } = coinDataApi

// In component:
import { useGetCurrenciesQuery } from '../services/coinDataApi'

const { data, isLoading } = useGetCurrenciesQuery()
console.log(data)

Any ideas on why I’m getting an unauthorized error?

hey, have u tried checking ur network tab in devtools? sometimes the error message there gives more details. also, make sure ur using the latest version of rtk query. old versions had some weird bugs with headers. oh and double check ur subscription on rapidapi dashboard, they can be sneaky with limits

The 401 Unauthorized error you’re encountering is likely due to an issue with your API key. Double-check that you’ve replaced ‘your-api-key-here’ with your actual RapidAPI key in the coinApiHeaders object. Also, ensure that your RapidAPI subscription is active and has sufficient credits.

Another potential issue is the baseUrl in your fetchBaseQuery. It should be the base URL without the endpoint. Try changing it to:

baseQuery: fetchBaseQuery({ baseUrl: 'https://cryptocurrencyranking.p.rapidapi.com' }),

Then, modify your getCurrencies query to:

getCurrencies: builder.query({
  query: () => prepareRequest('/currencies/list')
})

If these changes don’t resolve the issue, verify that you’ve correctly set up the middleware in your store configuration. Add this to your store.js:

middleware: (getDefaultMiddleware) =>
  getDefaultMiddleware().concat(coinDataApi.middleware),

This ensures that the API middleware is properly integrated with your Redux setup.

I’ve faced similar issues with RapidAPI before. One thing that helped me was double-checking the API documentation. Sometimes, the endpoint structure changes or there are specific requirements for query parameters.

Have you tried making the same request using a tool like Postman? This can help isolate whether the problem is with your Redux setup or the API itself. If it works in Postman but not in your app, you might want to compare the headers and request structure.

Also, make sure you’re not accidentally exposing your API key in your code repository. It’s a good practice to use environment variables for sensitive information like API keys. You could set up a .env file and use something like dotenv to load it:

const coinApiHeaders = {
  'X-RapidAPI-Host': 'cryptocurrencyranking.p.rapidapi.com',
  'X-RapidAPI-Key': process.env.REACT_APP_RAPIDAPI_KEY
}

This approach has saved me from accidentally pushing API keys to GitHub more than once!