0

I have class component for user sign up along with a form. I am making an api call based on user input to check if a user exists. The handleInputChange initially sets the state to some user input and the handleSubmit makes a call to another function which fetches from an endpoint. I want to set this.state.user to that response. I tried what was on this link but couldn't get it to work. Any ideas would help

import React, { Component } from 'react';

const user_add_api = "http://localhost:5000/add_user";
const user_check_api = "http://localhost:5000/user_by_username/";

here is the class:

class SignUp extends Component {
constructor(props) {
    super(props);

    this.state = {
        first_name: '',
        last_name: '',
        username: '',
        email: '',
        password: '', 
        user: ''
    };
}

checkUser = (user) => {
    const userPromise = fetch(user_check_api + user);
    var meh = '123meh';
    userPromise
        .then(data => data.json())
        .then(data => this.setState({user: {...this.state.user, meh}}))        


        // let curr = {...this.state};
        // curr['user'] = 'somevalue';
        // this.setState({ curr:curr['user'] });
    console.log(this.state.user);
}

handleSubmit = (event) => {
    event.preventDefault();
    const data = this.state;
    let s = this.checkUser(data.username);
    console.log(data);
}

handleInputChange = (event) => {
    event.preventDefault();
    this.setState({
        [event.target.name]: event.target.value, 
    })
}

render () {
    return (
        <form className="form-horizontal">
            <div className="form-group">
                <label className="col-md-4 control-label">First Name</label>  
                <div className="col-md-4">
                    <input name="first_name" type="text" placeholder="John" className="form-control input-md" required onChange={this.handleInputChange}></input>  
                </div>

                <label className="col-md-4 control-label">Last Name</label>  
                <div className="col-md-4">
                    <input name="last_name" type="text" placeholder="Doe" className="form-control input-md" required onChange={this.handleInputChange}></input>
                </div>

                <label className="col-md-4 control-label">Username</label>  
                <div className="col-md-4">
                    <input name="username" type="text" placeholder="John Doe" className="form-control input-md" required onChange={this.handleInputChange}></input>  
                </div>

                <label className="col-md-4 control-label">Email</label>  
                <div className="col-md-4">
                    <input name="email" type="text" placeholder="johndoe@example.com" className="form-control input-md" required onChange={this.handleInputChange}></input>
                </div>

                <label className="col-md-4 control-label">Password</label>
                <div className="col-md-4">
                    <input name="password" type="password" placeholder="" className="form-control input-md" required onChange={this.handleInputChange}></input>
                </div>


                <label className="col-md-4 control-label"></label>
                <div className="col-md-8">
                    <button name="save" onClick={this.handleSubmit} className="btn btn-success">Register</button>
                </div>
            </div>
        </form>
    );
 }
}

 export default SignUp;
anm
  • 1,865
  • 3
  • 19
  • 28
  • First of all do bind for your methods in your constructor. If you are not doing that your `this` scope is different inside your methods. For example, `this.checkUser = this.checkUser.bind(this)` – Observer Mar 01 '19 at 01:06
  • What about ```userPromise.then(() => this.setState((state) => {user: {...state.user, meh}}))```? – Arfeo Mar 01 '19 at 01:23

1 Answers1

0

This fetch(user_check_api + user) return a Promise and you not wait it. Maybe you should change like that

checkUser = (user) => {
    var meh = '123meh';
    fetch(user_check_api + user)
        .then(data => data.json())
        .then(data => {
                this.setState({user: {...this.state.user, meh}})
                console.log(this.state.user) // Show log in in success func
              })
}

Or use async/await

checkUser = async (user) => {
    const userPromise = await fetch(user_check_api + user);
    var meh = '123meh';
    userPromise
        .then(data => data.json())
        .then(data => this.setState({
                          user: {...this.state.user, meh} 
                       }, console.log(this.state.user))) // Show log in callback    
}
bird
  • 1,872
  • 1
  • 15
  • 32