Trying to handle errors with axios with React state and sweetalert2

Viewed 20

I've tried this a few different ways and can't seem to get it to work.

I am trying to handle an error when a user enters an already existing username. The backend works fine, however I am trying to get sweetalert to respond appropriately

front end react jsx

const [errors, setErrors] = useState({
        error: false,
        message: ''
    });

    const saveUser = async(userData) =>{

        await axios.post('/save_score', userData).then((res)=>{
            if(res.status === 200){
                Swal.fire({
                    icon: 'success',
                    title: 'Score saved!',
                    text: `${res.data.username} scored ${res.data.score} points`,
                    showCancelButton: true,
                    cancelButtonText: 'Hiscores',
                    confirmButtonText: 'Play again'
                })
            }
                                
        }).catch((err)=>{
            if(err.response.status === 400){
                setErrors({
                    error: true,
                    message: err.response.data.usernameError
                })
            }
        });
    }

const gameOver = (score) => {
        Swal.fire({
            title: 'Game over',
            text: `You scored ${score} points! Save your score?`,
            allowOutsideClick: false,
            showConfirmButton: true,
            showCancelButton: true,
            confirmButtonText: 'Yes',
            cancelButtonText: 'No'
        }).then((response)=>{
            if(response.isConfirmed){
                //user confirmed

                Swal.fire({
                    title: 'Enter your username',
                    input: 'text',
                    inputLabel: 'Username: ',
                    showCancelButton: true,
                    inputValidator: (value) => {
                        
                        if(!value){
                            return 'Must enter a username!';
                        } else {
                            var userData = {username: value, score: score};

                            saveUser(userData).then(()=>{
                                console.log(errors);
                            })
                        }
                        

                    }

                })
            } else {
                console.log('user cancelled');
            }
        })
    }

the problem I've been having with this specific attempt is that the state isn't changing. when I log after my saveUser().then(), the state comes back as its initialized even when I am trying to throw the username exists error.

I've also tried creating an error object, and inside the axios post's error, I set that objects error key to true and the errors response to that objects message key, but when that happens it seems axios post comes after any sort of error handling and it doesn't respond correctly.

let me know if this is enough info

0 Answers
Related