Sean
Sean

Reputation: 1456

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>

Upvotes: 1

Views: 1139

Answers (2)

Quentin Grisel
Quentin Grisel

Reputation: 4987

You can make your useEffect async :

useEffect(() => {
        async function myFunction() {
          let result = await fetch("http://localhost:3000/api/locations");
          let json =  await result.json();
          setLocs(data);
        }

        myFunction();        
}, [])

Upvotes: 0

Chemi Adel
Chemi Adel

Reputation: 2165

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:[]})

Upvotes: 2

Related Questions