1

I am trying to make api calls to Rapid API using react redux toolkit The code snippet

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

const cryptoApiHeaders = {
  "x-rapidapi-host": "coinranking1.p.rapidapi.com",
  "x-rapidapi-key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
};
const baseUrl = "https://coinranking1.p.rapidapi.com/coins";

const createRequest = (url) => ({ url });
export const cryptoApi = createApi({
  reducerPath: "cryptoApi",
  baseQuery: fetchBaseQuery({ baseUrl, prepareHeaders: cryptoApiHeaders }),
  endpoints: (builder) => {
    getCryptos: builder.query({
      headers: cryptoApiHeaders,
      query: () => createRequest("/coin"),
    });
  },
});

export const { useGetCryptosQuery } = cryptoApi;

If I run the app it gives an error with the createApi function. From debugging it is not able to make the api call hence, returning and empty object. I am not sure the right place to set headers in the function.enter image description here

VLAZ
  • 26,331
  • 9
  • 49
  • 67
fahad uddin
  • 51
  • 1
  • 6

2 Answers2

0

You need to call headers in createRequest. Like this: const createRequest = (url) => ({ url, headers: cryptoApiheaders});

And remove the headers from builder.query

0

prepareHeaders should be a function

https://redux-toolkit.js.org/rtk-query/api/fetchBaseQuery#common-usage-patterns

Viktor Kireev
  • 1,200
  • 1
  • 8
  • 17