Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot read property 'map' of undefined useEffect hook

When I console log locs.data I get an array, yet it says it is undefined..? Not sure what’s wrong with this.

let [locs, setLocs] = useState([])

    useEffect(() => {
        fetch("http://localhost:3000/api/locations")
        .then((res) => res.json())
        .then((data) => setLocs(data))
    }, [])
<Menu>
                        <MenuButton 
                            px={4}
                            py={2}
                            transition="all 0.2s"
                            borderRadius="md"
                            borderWidth="1px"
                            as={Button}
                            rightIcon={<ChevronDownIcon />}>
                            Location Links
                        </MenuButton>
                        <MenuList>
                         {locs.data.map(loc => (
                            console.log(loc)
                         ))}
                        </MenuList>
                    </Menu>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

printing runs before useEffect sometimes especially if you have async calls

try to check ifs it’s defined (true)

let [locs, setLocs] = useState()
...
<MenuList>
  {locs?.data?.map(loc => ( // ? suffix means continue if true
    console.log(loc)
  ))}
</MenuList>

OR change default state value to

let [locs, setLocs] = useState({date:[]})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading