简体   繁体   中英

Cannot read property 'map' of undefined [React.js]

so when i do my login and i try to redirect to this page it appears me that error it must be something with useEffect i dont know

here is my code

useEffect(() => {
    let canUpdate = true;
    getVets().then((result) => canUpdate && setVets(result));
    return function cleanup() {
        canUpdate = false;
    };
}, []);

const getVets = async () => {
    const url = 'http://localhost:8080/all/vet';
    const response = await fetch(url);
    const data = await response.json();
    setVets(data);
};

// const { appointmentType, animalID, room, hora, notes } = this.state;
return (
    <React.Fragment>
        <div class='title'>
            <h5>2 médicos vetenários disponíveis</h5>
        </div>
        <div>
            {vets.map((data) => (
                <ObterMedicos
                    key={data.name}
                    name={data.name}
                    specialty={data.specialty}
                />
            ))}
        </div>
    </React.Fragment>
);

}

vets might not have data on the first render and when the code tries to execute map operation on it, it gets undefined.map , which is not allowed.

You can either set vets to empty array at the time of defining the state

const [vets,setVets] = useState([]);

or just check on vets using Optional chaning (?) before using the map function:

{vets?.map((data) => (
                <ObterMedicos
                    key={data.name}
                    name={data.name}
                    specialty={data.specialty}
                />
            ))}

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