Reputation: 93
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
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
Reputation: 227
You are trying to render exchanges that you fetch asynchronously. Therefore, it is empty when the code starts to execute exchanges.map
block. 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