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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With