2022-02-16

Tech Programing

程式人小天地

useEffect don’t operates properly

2 min read


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="https://stackoverflow.com/">
     <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="https://stackoverflow.com/">
    <Button id='resource-download-button' name="downloadAll" onClick={updateForm} 
     variant="dark">
      Download All
      </Button>
      </a>
      </Col>
}
)



Source link

資料來源:Stackoverflow

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *