Home > Software engineering >  Redux Toolkit RTK Query sending query parameters is returning undefined
Redux Toolkit RTK Query sending query parameters is returning undefined

Time:03-30

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

CodePudding user response:

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.

  • Related