yung peso
yung peso

Reputation: 1796

React/MaterialUI - TypeError: Cannot read property 'map' of undefined

my mapping function initially worked until a few seconds ago, now I keep getting the error originally stated in the title. How can I fix this for my case below?

 export default function Graph()
 {
     const { slug } = useParams();
     const [data, setData] = useState([]);

    useEffect(() => {
        axiosInstance.get('bucket/' + slug + '/').then((res) => {
            setData(res.data);
            console.log(res.data.stock_list);
        });
     }, [setData, slug]);

    

     return (
         <Container>
             <Grid>
             <Paper>
                 <List dense component="div" role="list">
                 {data.stock_list.map((value) => {
                    return (
                        <ListItem role="listitem">
                            {value}
                        </ListItem>
                    );
                    })}
                </List> 
             </Paper>
             </Grid>
         </Container>
    ); 
 }

Upvotes: 0

Views: 38

Answers (1)

Josh Birdwell
Josh Birdwell

Reputation: 745

data.stock_list is undefined on the first render because you are initializing it to []. You could change to

    const [data, setData] = useState(); 
    ...
    {
      data?.stock_list?.map(value => <ListItem role="listitem">{value}</ListItem>)
    }

That way it won't continue unless data.stock_list is defined.

Upvotes: 2

Related Questions