Home > other >  How to setup like a function should be called only one time even after reload
How to setup like a function should be called only one time even after reload

Time:04-08

I'm trying to make a Post request on component Mount. But if user reloads the page or states changes, then the function is called again as I'm useEffect and it sends the request again. But I want any better thing where the Post request should be made once and if even the page refreshes the shouldn't be called again if it has been called.

I'm using the Function base component. and make Post requests using redux.

const Main = () => {
    // ....

   // Here I'm forcing user to login if there's user is logged in then want to make a silent post request, But it sends request everytime on state change.
   useEffect(() => {
    getLocalStorage()
    if (!userInfo) {
      setModalShow(true)
    }
    if (userInfo) {
      dispatch(postRequest())
      setModalShow(false)
    }
  }, [userInfo])
  return (
    <div>Some JSX </div>
  )
}

export default Main

So need your help to fix that issue. Can we use localStorage to store the information either the post request is already have been made or any other better idea?

CodePudding user response:

Best way is to use localstorage, not sure if my placements of setting ang getting value from localstorage are on the right spot.

const Main = () => {
    // ....

   // Here I'm forcing user to login if there's user is logged in then want to make a silent post request, But it sends request everytime on state change.
   useEffect(() => {
    getLocalStorage()
    // Check if the value of logged is true initiali will be false until the 
    // first request if made
    if (!!localStorage.getItem('logged')) {
      setModalShow(true)
    }
    if (userInfo) {
      dispatch(postRequest())
      setModalShow(false)
      // set the value when the request is finished
      localStorage.setItem('logged', true)
    }
  }, [userInfo])
  return (
    <div>Some JSX </div>
  )
}

export default Main

CodePudding user response:

There is a package named redux-persist that you can save the state, for example in localStorage. You can use this package, and send post request if there is not any data in state.

  • Related