Skip to content
Advertisement

Im getting an error in my react and rest api app where one of my variables is coming back undefined

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:

TypeError: errors is undefined
    submit UserSignUp.js:53
    promise callback*UserSignUp/this.submit UserSignUp.js:51
    React 17
    unstable_runWithPriority scheduler.development.js:653
    React 24
    js index.js:8
    Webpack 7

the part where this error is throwing is right here:

context.userController.createUser(user)
    .then( errors => {
      if (errors.length) {
        this.setState( {errors});
      } else {
        context.actions.signIn(emailAddress,password)
        .then( () => {this.props.history.push('/authenticated')}  );
      }
      })
    .catch( err => { // handle rejected promises
      console.log(err);
      this.props.history.push('/error'); // push to history stack
    })
  }
}

heres my createUser function code:

async createUser(user){
    const response = await this.call_api('/users', 'POST', user);
    if (response.status === 201) {
      return [];
    }
    else if (response.status === 400) {
      return response.json().then(data => {
        return data.errors;
      });
    }
    else {
      throw new Error();
    }
  }
  }

heres the code handiling post / users

router.post('/users', asyncHandler(async (req, res, next) => {
    const user = req.body;

    if(user.password)
    {
        user.password = bcryptjs.hashSync(user.password);
    };

    try
    {
        await User.create(user);
        res.status(201).location('/').end();
    } catch (error) {
        if (error.name === 'SequelizeValidationError' || error.name === 'SequelizeUniqueConstraintError')
     {
            const errorMsg = [];

            error.errors.map((err) => errorMsg.push(err.message));
            res.status(400).json({ error: errorMsg });
        } else
        {
            next(error);
        };
    };
}));

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.

 res.status(400).json({ errors: errorMsg });
Advertisement