Post request using Fetch not working from componentDidMount

691 views Asked by At

I would very much appreciate your help here pls. I am very new at web dev and in using ReactJS. I am trying to create a login page, using email and password as credentials. The issue is, if i put my fetch function in ComponentDidMount I get a 404 error, but if I take it out of the lifecycle method it connects to the server and i receive the user's details in the terminal - i don't yet know how to get them in the console or in my react app. If you could suggest a way to do that it would be much appreciated. I am trying to get the current user details that logs in.

This is my constructor method:

export default class Login extends React.Component {
  constructor(props){
    super(props);

this.state = {
  user:[],
  email:'',
  password:''
}

For the email and password inputs I have a handleChange function attached to the form: This is the function for the form inputs:

  handleChange = (e) =>{
   this.setState({
    [e.target.name]: [e.target.value]});
 } 

And this is the form:

        <input 
          type= "email"
          name="email"
          placeholder="Email address"
          value={this.state.email}
          onChange={event => this.handleChange(event)}
          required
        />
        <input
          type="password"
          name="password"
          placeholder="Password"
          value={this.state.password}
          onChange={event => this.handleChange(event)}
          required
        />

This is my fetch function in the lifecycle method:

 async componentDidMount(){
   const url = 'http://localhost:3000/login';
   const options = { method: 'POST',
   headers: {
       'Content-Type': 'application/json',
       'Accept': '*/*'
   },
   body: JSON.stringify({email:this.state.email, password:this.state.password})
   };

   const response = await fetch(url,options);
   let data = response.json();
   this.setState({user: data.results})
}

At this stage I get a 404 error in my console: ( POST http://localhost:3000/login 404 (Not Found) and in the terminal I get this error:

data:: {}
user:: []
user.length:: 0
TypeError: Cannot read property 'password' of undefined
at authenticateUser (/Users/noir/Documents/Dana/work/SocialCats/backend/controllers/login.js:16:16)
at processTicksAndRejections (internal/process/task_queues.js:97:5)

If i switch to Postman it works without problems, on the same url. As you can see in the picture..

If I take my fetch function out of the lifecycle method, then it works to authenticate the user and I get the users details in my terminal. Any idea why is this happening? Every help is greatly valued as I am quite stuck here. Thanks :)

1

There are 1 answers

0
Prateek Thapa On BEST ANSWER

Do the API call on when the user submits the form. At componentDidMount, the user has not entered email and password. Thus, your apiCall throws an error.

class Login extends React.Component {

  handleSubmit = (e) => {
      e.preventDefault();
      // do your API call here.
  }

  render() {
   return (
     <form onSubmit={handleSubmit}>
       /** all the other input tags */
     </form>
   )
  }
}