Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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>
)}
</>
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!