'React js - data.map is not a function

export default function Case() {
  const classes = useStyles();
  const[data,setData]=useState([])
  const getcovid=async()=>{
    const api=await fetch('https://api.rootnet.in/covid19-in/stats/latest');
    const res=await api.json();
    console.log(res.data.summary)
    setData(res.data.summary)
  }
  useEffect(()=>{
    getcovid()
  },[])
    
  return (
      
    <div>
        <Typography variant="subtitle1" gutterBottom>
        Material-UI Grid:
      </Typography>
        {
            data&&data.map(item=>{
                return(
                <Grid container spacing={3}>
                <Grid item xs={3}>
                  <Paper className={classes.paper}>Confirmed Cases: <br/>{item}</Paper>
                </Grid>
                <Grid item xs={3}>
                  <Paper className={classes.paper}>xs=3</Paper>
                </Grid>
                <Grid item xs={3}>
                  <Paper className={classes.paper}>xs=3</Paper>
                </Grid>
                
                
              </Grid>
                )  
              
            })
        }
       
     
      </div>
  );
}

My api - { "success": true, "data": { "summary": { "total": 26289290, "confirmedCasesIndian": 26289242, "confirmedCasesForeign": 48, "discharged": 23070365, "deaths": 295525, "confirmedButLocationUnidentified": 0 },

But it shows an error - TypeError: data.map is not a function I have tried both with data&&data.map and only with data.map but still i get same errorenter code here



Solution 1:[1]

Your data is an object not an array. You can try to use this instead:

Object.keys(data).map(function(key, item) {
  console.log(data[key]);
   return(

    ...
   )
});

Solution 2:[2]

The API response you posted shows that data.summary is an object, not an array. Objects don't have a map method, but arrays do. Instead of using map you can just access the properties individually, such as {data.total} and {data.deaths}.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 programandoconro
Solution 2 Matt U