Home > Software engineering >  useEffect don't operates properly
useEffect don't operates properly

Time:02-16

I am working on react.js . My requirement is to perform an API call on closing the tab. Once tab/browser is closed an event is triggered, from that triggered event an API will be called to store values in DB. I have written the code in useEffect() but the API fetches each time on button click due to this false value is stored in the DB . I have added my code . Can someone point out the mistake in my code and provide me a proper solution.

const [formRegistered, setFormRegistered] = useState(false)

 const initialFormState = {
    firstname: '',
    lastname: '',
    email: '',
    company: '',
    presentation: false,
    keyTakeaways: false,
    whitepaper: false,
    downloadAll: false
  }


  useEffect(() => {
    return () => {
      if( formRegistered){
         window.addEventListener("beforeunload", function(e) {
        e.preventDefault();
       let confirmationMessage =  "";
       (e || window.event).returnValue = confirmationMessage;
       handleSubmit(e)
     return confirmationMessage ; 
    
    });
   }
  }
  });

  
  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 == 'presentation') {
      dispatch({ type: 'INSERT', field: 'presentation', payload: true })
    } else if (e.target.name == 'keyTakeaways') {
      dispatch({ type: 'INSERT', field: 'keyTakeaways', payload: true })
    } else if (e.target.name == 'whitepaper') {
      dispatch({ type: 'INSERT', field: 'whitepaper', payload: true })
    } else 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/sample-API', {
          method: 'POST',
          body: JSON.stringify({ response: formState, type: 'download', anonymousID: 
          anonymousID })
        })
       
        setFormRegistered(false)
      }

return (

  { formRegistered && <Col className='resource-download-button-container' sm={12} lg={4}>
     <a target='_blank' download href='/'>
     <Button id='resource-download-button' name='whitepaper' onClick={updateForm} 
      variant='dark'>
       Whitepaper
       </Button>
      </a>
      </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>
}
)

CodePudding user response:

useEffects clean callback fires only while unmounting component... not while closing application... For this purpose i suggest to create eventListener for beforeUnload event:

useEffect(()=>{
 window.addEventListener("beforeunload", onUnload);
 return ()=> window.removeEventListener("beforeunload", onUnload)}
,[]);

CodePudding user response:

Currently your useEffect() hook will be called on each operation because it doesn't listen to a specific value change.

What you need to include to your useEffect hook is something like this:

useEffect(() => {
// your api call
}, [formRegistered]};

By adding [formRegistered] after your function definition inside your useEffect hook, the hook will only be executed if the value of formRegistered changes, instead of executing on every click.

Edit: I have just tested it myself and you are correct, this does not work when closing tabs. I have achieved your desired result by implementing it like this:

useEffect(() => {
  const executeOnClose = () => {
    // your api call
  }

  window.addEventListener('beforeunload', executeOnClose);

  return () => {
    window.removeEventListener('beforeunload', executeOnClose);
  }
}, []);
  • Related