---
# System prepended metadata

title: React 用 api 取資料踩坑

---

# 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/ㄊ