I have this code and it the result is Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'data')
My create account function is giving me this error
const sendRequest = async () => {
if (!name || !email || !password) return;
const user = { name, email, password };
const res = await axios
.post('/api/v1/auth/register', {
user,
})
.catch((err) => console.log(err));
const data = await res.data;
return data;
};
const handleSubmit = (e) => {
e.preventDefault();
sendRequest().then(() => setMloggi(true));
};
CodePudding user response:
the respnse result might be an error. Hence it's not returning a data property. Check if data exists and no need to await again
if(res.data)
return data;
return [] // or an object. whatever the standard response
also, no need to use then
here since the result is already resolved
const result = sendRequest()
if(result) setMloggi(true)
CodePudding user response:
- I suggest using
try catch
block instead of.then
,.catch
while usingasync await
. - Getting
TypeError
because access something inres
which doesn't exist
const sendRequest = async () => {
if (!name || !email || !password) return;
const user = { name, email, password };
try {
const res = await axios.post("/api/v1/auth/register", {
user,
});
const data = await res?.data ||"not found";
return data;
} catch (err) {
console.log(err);
}
};