Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optional chaining and useState hook

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading