I get undefined if I replace my line 17 with cryptoInfo?.map .I used cryptoInfo in the useState hook.Is this due to the error in useState
const Cryptocurrencies = ({ simplified }) => {
let count = simplified ? 10 : 100;
const { data: cryptoList, isFetching } = useGetCryptosQuery(count);
const [cryptoInfo, setCryptoInfo] = useState(cryptoList?.data?.coins);
console.log(cryptoInfo);
if (isFetching) return "Loading...";
return (
<>
<Row gutter={[16, 16]} className="crypto-card-container">
{cryptoList?.data?.coins?.map((currency) => (
<Col
xs={24}
sm={12}
xl={6}
className="crypto-card"
key={currency.uuid}
>
</Col>
))}
</Row>
</>
);
};
export default Cryptocurrencies;
>Solution :
I assume your problem is that cryptoInfo is initialised with undefined because useGetCryptosQuery(count) seems to be an async function, that returns a value that is initially undefined and later gets updated – but at that point in time cryptoInfo is already initialised with undefined and does not get updated with the new value.
The quick fix would be to use useEffect to keep cryptoInfo always up to date:
useEffect(
() => setCryptoInfo(cryptoList?.data?.coins),
[cryptoList]
);