简体   繁体   中英

Fetch Get Request in React 'Cannot read property 'map of undefined'

I am attempting to make a fetch GET request in React. I'm new to this and having a bit of trouble understanding the response structure. I'm currently hitting a server with this code and trying to put it in a table. But i keep getting the error Unhandled Rejection (TypeError): Cannot read property 'map' of undefined . Can anyone explain to me where I've gone wrong or what to do?

const [rowData, setRowData] = useState([]);

  const columns = [
    { headerName: "Stock", field: "name"}, 
    { headerName: "Symbol", field: "symbol" }, 
    { headerName: "Industry ", field: "industry" }
  ];

useEffect(() => {
    fetch("PRIVATE SERVER")
    .then(res => res.json())
    .then(json => console.log(json))
    .then(data => 
      data.map(stocks => {
        return {
          name: stocks.name,
          symbol: stocks.symbol,
          industry: stocks.industry,
        };
      })
    )
    .then(stocks => setRowData(stocks));
  }, []);

This is an example of what the JSON response from the server looks like:

[
  {
    "name": "Agilent Technologies Inc",
    "symbol": "A",
    "industry": "Health Care"
  },
  {
    "name": "American Airlines Group",
    "symbol": "AAL",
    "industry": "Industrials"
  }
]

The problem is actually with your usage of then. You should try to do a different approach on your code.

For example

  const [rowData, setRowData] = useState([]);

  const columns = [
    { headerName: "Stock", field: "name"}, 
    { headerName: "Symbol", field: "symbol" }, 
    { headerName: "Industry ", field: "industry" }
  ];

useEffect(() => {
    fetch("PRIVATE SERVER")
    .then(res => res.json()
       .then(json => {
          console.log(json);
          const newRowData = json.map(stocks => {
             return {
                name: stocks.name,
                symbol: stocks.symbol,
                industry: stocks.industry,
             };
          });
          setRowData(newRowData);
       }));

But I suggested you try async-await for the sake of code readability

const [rowData, setRowData] = useState([]);

  const columns = [
    { headerName: "Stock", field: "name"}, 
    { headerName: "Symbol", field: "symbol" }, 
    { headerName: "Industry ", field: "industry" }
  ];

useEffect(() => {
   async function doFetch() {
      const fetchResponse = await fetch('PRIVATE SERVER', { method: 'GET' });
      if (response.status !== 200) // do something

      // extract the json string to json object
      const data = await fetchResponse.json();

      const newRowData = data.map(stocks => ({
         name: stocks.name,
         symbol: stocks.symbol,
         industry: stocks.industry,
      }));

      setRowData(newDataRow);
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM