Home > Net >  preventDefault unless form is successfully submitted
preventDefault unless form is successfully submitted

Time:10-27

I have a user form to submit blog posts. I want to display errors on the form if users do not enter acceptable data or miss a field. I used event.preventDefault(); to keep the page from reloading when they push submit. Everything works how I want it to, accept I want the page to reload after the form is successfully submitted. as of right now, the data from the form will submit, but it will not reload the page. How can I get it so the page and form reload as soon as the form successfully submits, but not when there are errors?

Here is my jsx

import React from 'react'
import fireIconImage from '../images/fireIcon.png'
import FireIcon from './FireIcon'


export default function BlogPostForm () {
    const [formState, setFormState] = React.useState({ flaire: '', title: '', text: '', fireLevel: ''});
    const [isHovered, setIsHovered] = React.useState();
    const [isLit, setIsLit] = React.useState();
    const [formErrors, setFormErrors] = React.useState({});

    /*need to start implementing the validation states,
    /*will need an errorState object with a specified error for each field*/
    


    /*handleChange for input fields*/
    function handleChange(e) {
        const { name, value } = e.target;
        setFormState({...formState, [name]: value})
    }

    /*functions for fire icon handling*/
    function handleMouseOver(e) {
        setIsHovered(e.target.id);
    }

    function handleMouseLeave(e) {
        setIsHovered();
    }

    function handleFireIconClick(e) {
        setIsLit(e.target.id);
        setFormState((prevFormState) => ({...prevFormState, fireLevel: e.target.id}))
    }


    function handleFireIconClass(fireLevel) {
        const classNames = ['fireIcon']
            classNames.push(`fireIcon${fireLevel}`)
            if (isHovered >= fireLevel) {
                classNames.push('isHeld')
            }
            if (isLit >= fireLevel) {
                classNames.push('isLit')
            }
        return classNames.join(' ');
        
    }

    /*render 5 fireIcons */

    const fireIconsArray = [];

    for (let i = 0; i < 5; i  ) {
        fireIconsArray.push(
            <FireIcon 
                onClick={handleFireIconClick}
                onm ouseLeave={handleMouseLeave}
                onm ouseOver={handleMouseOver}
                className={handleFireIconClass(i 1)}
                src={fireIconImage}
                alt="fire icon"
                id={i 1}
                key={i 1}
            />
        )
    }



    /*submit function*/
    function validate(values) {
        const errors = {}
        if(!values.flaire) {
            errors.flaire = "Flaire is required!"
        }
        if(!values.title) {
            errors.title = "Title is required!"
        }
        if(!values.text) {
            errors.text = "Text is required!"
        }
        if(!values.fireLevel) {
            errors.fireLevel = "Select a fire level!"
        }
        return errors;

    }

    function submitForm(event) {
        event.preventDefault();
        const errors = setFormErrors(validate(formState));
        if (errors) {
            console.log(errors)
            return;
        }
        /*post to database*/
            const data = formState;
            const options = {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            }
            fetch('http://localhost:8000', options);
          
    }


    /*blogPostForm jsx*/
    
    return (
        <form className="postForm">
            <h1 className="postFormHeader">Create a blog post!</h1>        
                <select
                    required
                    className="flaireSelect" 
                    name="flaire"
                    value={formState.flaire}
                    onChange={handleChange}>
                        <option disabled={true} value="">Choose a flaire</option>
                        <option value="JavaScript">JavaScript</option>
                        <option value="CSS">CSS</option>
                        <option value="HTML">HTML</option>
                        <option value="REACT">REACT</option>
                        <option value="BACKEND">BACKEND</option>
                </select>
                {formErrors.flaire && <p className="inputError inputErrorCenter">{ formErrors.flaire }</p> }
                <input
                    value={formState.title}
                    onChange={handleChange}
                    className="titleBox"
                    placeholder="title"
                    type="text"
                    id="title"
                    name="title"
                />
               {formErrors.title && <p className="inputError">{ formErrors.title }</p> }
                <textarea
                    value={formState.text}
                    onChange={handleChange}
                    className="textBox"
                    placeholder="text"
                    type="text"
                    id="blogPost"
                    name="text"
                />
                {formErrors.text && <p className="inputError">{ formErrors.text }</p> }
                <div className="fireIconContainer">
                    {fireIconsArray}
                </div>  
                {formErrors.fireLevel && <p className="inputError inputErrorCenter">{ formErrors.fireLevel }</p> }
                <div className="blogPostFormButtonContainer">
                    <button className="blogPostSubmit" type="submit" onClick={submitForm}>SUBMIT</button>
                    <button className="blogPostCancel" type="submit">CANCEL</button>
                </div>

        </form>
    )
}

CodePudding user response:

If you want to reload the page after a successful save, then after fetch() call .then() & then call window.location.reload() to reload the page

As an example:

function submitForm(event)
{
    event.preventDefault();
    const errors = setFormErrors(validate(formState));
    if (errors)
    {
        console.log(errors)
        return;
    }
    /*post to database*/
    const data = formState;
    const options = {
        method: 'POST',
        headers:
        {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    }
    fetch('http://localhost:8000', options)
    .then((response) => window.location.reload()); // You might want to check the status code or response.

CodePudding user response:

You can check the length of the Object that validate() returns to check if there are errors, and if there are none, then you can continue, like so:

function submitForm(event) {
    if (!Object.keys(validate(formState)).length === 0) {
        event.preventDefault();
        console.log(errors);
        return;
    }
    // ...
}

Or place the preventDefault into your errors check, like so:

if (errors) {
    event.preventDefault();
    console.log(errors);
    return;
}

Believe it or not, preventDefault() is not limited to an event handler scope.

  • Related