4

So in redux toolkit you're able to create hooks that call to a RestApi using multiple endpoints, I'm using 3 endpoints which using redux-toolkit it creates 3 hooks that I can use anywhere in my react application, my question is how do I get it to work all in one component?

import React from "react";
import { useSelector } from "react-redux";
import { useGetCountryQuery, useGetRegionQuery, useGetAllQuery } from "../../services/CountryAPI";
import CountryCard from "./CountryCard";
import { Link } from "react-router-dom";

const CountryList = () => {
  const { option } = useSelector((state) => state.option);
  const { data = [], isFetching } = useGetAllQuery();
  const { data = [], isFetching } = useGetCountryQuery();
  const { data = [], isFetching } = useGetRegionQuery(option);

  return (
      <>
          {data.map((country) => (
            <Link onClick={() => {}} key={country.name.official} to={`/details/${country.name.official}`} >
                <CountryCard
                    key={country.name.official}
                    name={country.name.official}
                    capital={country.capital}
                    region={country.region}
                    population={country.population}
                    flag={country.flags.svg}
                />
            </Link>
        ))}
    </>
);
};

export default CountryList;

As you can see I have to destructure "data" and "isFetching" for all three hooks which is how I know functions, What is an alternative way for me to use all three API hooks so i can use it on the same component being "CountryCard" I want to display?

1 Answer 1

7

For one, you could decide to just not destructure.

  const allResult = useGetAllQuery();
  const countriesResult = useGetCountryQuery();
  const regionResult= useGetRegionQuery(option);

  return (
      <>
          {countriesResult.data?.map((country) => (

Or, you rename things while destructuring:


  const { data: all = [], isFetching: allFetching } = useGetAllQuery();
  const { data: countries = [], isFetching: countryFetching } = useGetCountryQuery();
  const { data: regions = [], isFetching: regionFetching } = useGetRegionQuery(option);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you this solved my issues, Keep up the amazing work!!

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.