skip to Main Content

I have some interesting behaviour that I’m trying to understand in my React Application below. I’m finding form values aren’t resetting when a user starts a new form submission and I’m trying to understand why.

We have a Dashboard component, which had a button allowing users to create a new project.

The button is below:

     <HrefLink
         to={"/project/new"}
         state={{ projects: rows }}
     >
         <Button id="newProject" variant="contained" size="Small">
             New
         </Button>
    </HrefLink>

Fairly simple stuff. Under the NewProject route, we import defaultValues for new projects via a constants file:

    import { defaultValues } from "../constants/consts";

    export default function NewProject() {
        const [formValues, setFormValues] = useState(defaultValues);
        ...
        ...
    }

consts.jsx:

    export const defaultValues = {
        name: "",
        description: "",
        startDate: new Date(new Date().setHours(0, 0, 0, 0)),
        endDate: "",
        status: "DRAFT"
    }

Again, fairly simple. However, I’m finding what’s happening is I can start a new form, go through the steps, enter values, etc (I am running on localhost). Then, without submitting the form – I just click back home instead, I can come back to my application the next day, and I find when I start a new form again, the startDate is being set as the previous day instead of today’s date. I.E: a new form is not being set with the default values.

Just this morning I can see:
formValues.startDate:
Tue Nov 21 2023 00:00:00 GMT+1300 (New Zealand Daylight Time)

Todays actual date if using new Date(new Date().setHours(0, 0, 0, 0)) should be:
Wed Nov 22 2023 00:00:00 GMT+1300 (New Zealand Daylight Time)

Looks like the state isn’t being reset if a user doesn’t submit the form, so I’m wondering how I can force this reset to occur. Any suggestions?

2

Answers


  1. Chosen as BEST ANSWER

    I was also able to make the below updates to reset the state:

    consts.jsx:

        export const defaultValues = () =>{
          return{
            name: "",
            description: "",
            startDate: new Date(new Date().setHours(0, 0, 0, 0)),
            endDate: "",
            status: "DRAFT"
          }
        }
    

    and then:

    [formValues, setFormValues] = useState(defaultValues())
    

  2. You can use the clean up function from useEffect which will run uncomponent unmounts so in you case that could clear the form state

    useEffect(() => {
      // Anything in here is fired on component mount.
      return () => {
        // Anything in here is fired on component unmount.
    
      }
    }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search