'Losing the value on submitting in react js

I am working on react.js . I need to submit a form while attempting to close the tab. I have written a code in useEffect to trigger an event while closing the tab. I am have a button while clicking on it the state value changes to true. My issue : On submitting the Boolean (downloadAll) value retains to initial false value and that value will be submitted and stored in DB.I have a doubt whether is it due to preventDefault(). I am not sure about it. If someone know the correct reason please help to solve my problem

const initialFormState = {
        downloadAll: false
        firstname: '',
  }

useEffect(() => {
    const executeOnClose = (e) => {
      e.preventDefault();
      if(formRegistered){
      let confirmationMessage =  "";
      (e || window.event).returnValue = confirmationMessage;
      handleSubmit(e)
      return confirmationMessage ; 
      }
    }
  
    window.addEventListener('beforeunload', executeOnClose);
  
    return () => {
      window.removeEventListener('beforeunload', executeOnClose);
    }
  }, [formRegistered]);

function formReducer(state, action) {
    switch (action.type) {
      case 'INSERT':
        return { ...state, [action.field]: action.payload }
      default:
        return state
    }
  }

const [formState, dispatch] = useReducer(formReducer, initialFormState)
  
  const updateForm = (e) => {
    if (e.target.name == 'downloadAll') {
      dispatch({ type: 'INSERT', field: 'downloadAll', payload: true })
    } else {
      dispatch({ type: 'INSERT', field: e.target.name, payload: e.target.value })
    }
  }

 const handleSubmit = async (e) => {
    e.preventDefault()
   const result = await fetch('/api/test-api', {
      method: 'POST',
      body: JSON.stringify({ response: formState, type: 'download', anonymousID: anonymousID })
    })
   
    setFormRegistered(false)
  }

return(

<>
<form className={'download-form'} onSubmit={handleSubmit}>
          {!formRegistered ? (

<Form.Group as={Row} className='mb-3' controlId='formGroupName'>
      <Form.Label column sm={12}>
           Name *
       </Form.Label>
       <Col sm={12} lg={6}>
         <Form.Control className='mb-3' name='firstname' type='text' 
           onChange={updateForm} placeholder='Enter First name' required />
       </Col>

      <Col className='resource-download-button-container' sm={12} lg={12}>
          <a target='_blank' download href='/'>
            <Button id='resource-download-button' name='downloadAll' onClick={updateForm} 
             variant='dark'>
             Download All
             </Button>
           </a>
       </Col>
  </Form.Group>

</form>
)}
</>


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source