Ashley Ferns
Ashley Ferns

Reputation: 93

Please solve this error - Uncaught TypeError: Cannot read properties of undefined (reading 'map')

react-refresh-runtime.development.js:315 Uncaught TypeError: Cannot read properties of undefined (reading 'map')

const Exchange = () => {
  const { exchanges, setExchanges } = useState([]);
  const { loading, setLoading } = useState(true);

  useEffect(() => {
    const fetchExchanges = async () => {
      const { data } = await axios.get(`${server}/exchanges`);
      // console.log(data);
      setExchanges(data);
      setLoading(false);
    };
    fetchExchanges();
  });
  return (
    <Container maxW={"container.xl"}>{loading ? ( <Loader /> ): (<>
        <HStack>
            {exchanges.map((i) => 
             (
                    <div>{i.name}</div>
                ))}
        </HStack>
    </>)}
    </Container>
  );
};

Upvotes: 2

Views: 1440

Answers (2)

Ashley Ferns
Ashley Ferns

Reputation: 93

instead of

const { exchanges, setExchanges } = useState([]);
  const { loading, setLoading } = useState(true);

this

  const [ exchanges, setExchanges ] = useState([]);
  const [ loading, setLoading ] = useState(true);

Upvotes: 2

Ahmet Ulutaş
Ahmet Ulutaş

Reputation: 227

You are trying to render exchanges that you fetch asynchronously. Therefore, it is empty when the code starts to execute exchanges.mapblock. You can't map an empty array and get i.name out. Try waiting it to be filled with axios call by adding optional chaining.

exchanges?.map((i) =>  .........

Upvotes: 1

Related Questions