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>
);
};
CodePudding user response:
instead of
const { exchanges, setExchanges } = useState([]);
const { loading, setLoading } = useState(true);
this
const [ exchanges, setExchanges ] = useState([]);
const [ loading, setLoading ] = useState(true);
CodePudding user response:
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) => .........