Post current React state to express server

Issue

I have tried a few different ways of doing this but no matter what I’ve tried I get the same result.

Once I start the server, the first time I post, it doesn’t work. because the state hasn’t updated (I think)? All of the following post requests afterwards work fine, along with the correct state. So I’m not so sure it’s state. Here’s my code

Register.js

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

        this.state = {
            username: '',
            password: ''
        }
    }

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

    register = async () => {
        
        await axios.post(config.API_URI + 'register', {
            username: this.state.username,
            password: this.state.password
        });
    }
    

    render(){
        return(
            <div>
                <form id='register-form' className='border'>
                    <div id='form-title'>Create account</div>
                    <div className='mb-3'>
                        <label className='form-label' htmlFor='username-label' name='username-label'>Username</label>
                        <input type='text' className='form-control' id='usernameInput' name='username' onChange={this.onChange}></input>
                    </div>
                    <div className='mb-3'>
                        <label className='form-label' htmlFor='password-label' name='password-label'>Password</label>
                        <input type='password' className='form-control' id='password-input' name='password' onChange={this.onChange}></input>
                    </div>
                    {/*}
                    <div className='mb-3'>
                        <label className='form-label' htmlFor='password-label-confirm' name='password-label-confirm'>Confirm Password</label>
                        <input type='password' className='form-control' id='password-input-confirm' name='passwordConfirm'></input>
                    </div>
                    {*/}
                    <div id='buttons'>
                        <button className='btn btn-primary' id='register-btn' onClick={this.register} disabled={this.state.username === '' & this.state.username === ''}>Register</button>
                        <Link className='btn btn-primary' to='/login' id='login-btn'>Login</Link>
                    </div>
                </form>
            </div>
        )
    }
}

server.js post request (currently just attempting to console.log my request instead of adding to my database). I have gotten it to save to the database just fine following the second post attempt.

...

app.post("/register", (req, res)=>{
    try{
        if(req.body){
            console.log(req.body);
            /*
            User.find({username: req.body.username}, (err, data)=>{

                if(data.length == 0){

                    let user = new User({
                        username: req.body.username,
                        password: req.body.password
                    });

                    user.save((err,data)=>{
                        if(err){
                            res.status(400).json({
                                errorMessage: err,
                                status: false
                            });
                        } else {
                            res.status(200).json({
                                status: true,
                                title: 'Registered Successfully'
                            });
                        }
                    });
                }
            });
            */
        }
    } catch(e){
        res.status(400).json({
            errorMessage: 'Something went wrong!',
            status: false
        })
    }
});

I’m a beginner making my first full-stack application

Solution

Good night! I cannot comment because I’m too new to Stack Overflow, so I’ll say the following as an answer:

I ran your code on my machine and it worked fine but the reload. When I clicked on the "Register" button, I read the current state value by adding console.log(this.state) just before await axios.post(...).
That worked since the first click. However, the page reloads each submition. You missed the event.preventDefault(). This function prevents the reload when submitting a form by clicking on a button inside it. This is the code:

register = async (event) => {
  event.preventDefault();

  await axios.post('http://localhost:3333/register', {
    username: this.state.username,
    password: this.state.password
  });
}

Then, I ran a Node API with your code. It also console.log(req.body) worked perfectly fine as well.

Therefore, I don’t have any other ideas of what could be causing the issue on your machine besides the missing event.preventDefault().

P.S.:

Some features that helps while debugging JavaScript:

  • Use the command debugger; on your Front-End code. For example, inside the register method. This allows you to stop the execution of the code and inspect all the variables available and their current values. This may help you.
  • While debugging don’t forget to put a lot of console.log on your code in specific parts that could be related to your bug. This helps you understand what’s going on.

Answered By – marcel099

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published