0

How do you pass query parameters to the api using Redux Toolkit RTK Query without getting it being undefined?

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

const cryptoApiHeaders = {
  "X-RapidAPI-Host": "...",
  "X-RapidAPI-Key": "...",
};

const baseUrl = "...";

const createRequest = (url) => ({ url, headers: cryptoApiHeaders });

export const cryptoApi = createApi({
  reducerPath: "cryptoApi",
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (name) => createRequest(`/coins?limit=${name}`),
    }),
  }),
});

export const { useGetCryptosQuery } = cryptoApi;

When I pass the parameter down from the component, Its either It does not pass or it does not seem to recognize it, because it always shows undefined https://.../coins?limit=undefined. I really don't know what I'm doing wrong.

import React, { useState } from "react";
import millify from "millify";
import { Link } from "react-router-dom";
import { Card, Row, Col, Input } from "antd";

import { useGetCryptosQuery } from "../services/cryptoApi";

const Cryptocurrencies = () => {
  const count = 10;
  const { data: cryptosList, isFetching } = useGetCryptosQuery(count);
  const [cryptos, setCryptos] = useState(cryptosList?.data?.coins);

  return (
    <>
      <Row gutter={[32, 32]} className="crypto-card-container">
        {cryptos.map((currency) => (
          <Col xs={24} sm={12} lg={6} className="crypto-card" key={currency.id}>
            <Link to={`/crypto/${currency.uuid}`}>
              <Card
                extra={
                  <img
                    className="crypto-image"
                    src={currency.iconUrl}
                    alt={`${currency} currency`}
                  />
                }
                title={`${currency.rank}. ${currency.name}`}
                hoverable
              >
                <p>Price: {millify(currency.price)}</p>
                <p>Market Cap: {millify(currency.marketCap)}</p>
                <p>Daily Change: {millify(currency.change)}%</p>
              </Card>
            </Link>
          </Col>
        ))}
      </Row>
    </>
  );
};

export default Cryptocurrencies;

I tried hard coding it by putting value directly in the query and it worked perfectly without showing the undefined.

export const cryptoApi = createApi({
  reducerPath: "cryptoApi",
  baseQuery: fetchBaseQuery({ baseUrl }),
  endpoints: (builder) => ({
    getCryptos: builder.query({
      query: (name = 10) => createRequest(`/coins?limit=${name}`),
    }),
  }),
});

why can't I send the value from another component

1 Answer 1

1

The problem is that you are initializing your cryptos state with undefined on first render and that useState calls never update when they are called with a different initialValue.

Just remove that useless useState and leave

  const { data: cryptosList, isFetching } = useGetCryptosQuery(count);
  const cryptos = cryptosList?.data?.coins;

and everything will work fine.

PS: what tutorial is that? I have seen quite a bit of SO posts with that weird (and honestly quite pointless) createRequest function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.