# React 用 api 取資料踩坑 ## "Cannot read property 'map' of undefined" Error in React ```react.js= const [balanceData, setBalanceData] = useState([]); const [loading, setLoading] = useState(false); const classes = useStyles(); useEffect(() => { setLoading(true); fetch("/get_balance") .then((res) => { if (res.ok) { return res.json(); } }) .then((data) => { setBalanceData(data); }) .catch((err) => { console.log(err); }) .finally(() => { setLoading(false); }); }, []); ``` * 若useState()沒給預設值,當資料還沒到位,此時map沒有東西報錯 ## Reference https://typeofnan.dev/fix-cannot-read-property-map-of-undefined-error-in-react https://www.debuggr.io/react-map-of-undefined/ㄊ
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up