score:0

Accepted answer

to put it simply, i would suggest i suggest turning your handlesubmit into this:

handlesubmit(event) {
    event.preventdefault();

    this.postuserinfo().then(()=>{

        return this.getuserinfo();

    }).then(()=>{

        console.log("userinfo: " + this.state.usersinfo)
        alert('username was submitted: ' + this.state.userinput);
        this.setstate({
            showinicio: !this.state.showinicio
        });

    });
}

and do this in your postuserinfo and getuserinfo methods:

postuserinfo(){
    return fetch("http://localhost:8080/api/users", {
        method: "post",
        mode: "cors",
        headers: {
            "content-type": "application/json",
        },
        body: json.stringify({ username: this.state.userinput, bestattempts: 0, besttime: 0 })
    })
    .then((res) => res.json())
    .then(data => {
        console.log(data);
        this.setstate({ dataposted: true });
    })
    .catch((error) => {
        console.log(error);
    })

}
getuserinfo() {
    return fetch("http://localhost:8080/api/users", { mode: "cors" })
        .then((res) => res.json())
        .then(data => { //you had a syntax mistake here: (data
            this.setstate({ usersinfo: data })

            const _head = {
                id: "id",
                username: "username",
                bestattempts: "best attempts",
                besttime: "best time",
            }
            this.setstate({ head: _head })
        })
}

there's no need to use async/await as the fetch api already uses promises.

the reason you were getting the weird error may have been because you were trying to preventdefault() inside of an async function. is because preventdefault is being executed after the first await

thanks to bravo for clarifying.


Related Query

More Query from same tag