thank you for your time if youre reading this, im making a full stack app with react and rest api and im encountering an error as such:
JavaScript
x
9
1
TypeError: errors is undefined
2
submit UserSignUp.js:53
3
promise callback*UserSignUp/this.submit UserSignUp.js:51
4
React 17
5
unstable_runWithPriority scheduler.development.js:653
6
React 24
7
js index.js:8
8
Webpack 7
9
the part where this error is throwing is right here:
JavaScript
1
16
16
1
context.userController.createUser(user)
2
.then( errors => {
3
if (errors.length) {
4
this.setState( {errors});
5
} else {
6
context.actions.signIn(emailAddress,password)
7
.then( () => {this.props.history.push('/authenticated')} );
8
}
9
})
10
.catch( err => { // handle rejected promises
11
console.log(err);
12
this.props.history.push('/error'); // push to history stack
13
})
14
}
15
}
16
heres my createUser function code:
JavaScript
1
16
16
1
async createUser(user){
2
const response = await this.call_api('/users', 'POST', user);
3
if (response.status === 201) {
4
return [];
5
}
6
else if (response.status === 400) {
7
return response.json().then(data => {
8
return data.errors;
9
});
10
}
11
else {
12
throw new Error();
13
}
14
}
15
}
16
heres the code handiling post / users
JavaScript
1
26
26
1
router.post('/users', asyncHandler(async (req, res, next) => {
2
const user = req.body;
3
4
if(user.password)
5
{
6
user.password = bcryptjs.hashSync(user.password);
7
};
8
9
try
10
{
11
await User.create(user);
12
res.status(201).location('/').end();
13
} catch (error) {
14
if (error.name === 'SequelizeValidationError' || error.name === 'SequelizeUniqueConstraintError')
15
{
16
const errorMsg = [];
17
18
error.errors.map((err) => errorMsg.push(err.message));
19
res.status(400).json({ error: errorMsg });
20
} else
21
{
22
next(error);
23
};
24
};
25
}));
26
Im really not sure whats going on with my errors variable here so if anyone could help me that would be great heres my github link: https://github.com/zakMossy/react-and-rest-api-project-10
Advertisement
Answer
Your createUser
function code returns data.errors
if the response status is not 201. But your API sends the errors in the error
key. Update the key to errors
in your API route handler and you should be good to go.
JavaScript
1
2
1
res.status(400).json({ errors: errorMsg });
2