-1

I am working on a project using vue JS and inertia JS, basically I wanna trigger this code ONCE when the page loads or reloads.

router.visit('/getrequest',{
        method:'get'
})

but its triggering nonstop even if I wrap it with onMounted() still the same issue.

onMounted(() => {
        router.visit('/getrequest',{
        method:'get'
        })
   })

hopefully someone can pin point what i am missing here.

thanks

1
  • You could probably have it in a global JS file or App.vue so that it's not unmounted/mounted again, hence triggering the whole code again.
    – kissu
    Commented Mar 5 at 16:47

1 Answer 1

0

Consider using a session storage to keep track whether the page has been loaded or not, in the onMounted you'll check whether the page has been loaded already and if so you'll skip the router.visit logic like this:

onMounted(() => {
  if (!sessionStorage.getItem('hasFetched')) {
    sessionStorage.setItem('hasFetched', 'true')
    router.visit('/getrequest', { method: 'get' })
  }
})

More information on the sessionStorage approach

How it works:

  1. When the page loads, onMounted() runs.
  2. We check sessionStorage.getItem('hasFetched'). If it doesn't exist, it basically means its the first load so we will make the router.visit() request In that case we will also set the sessionStorage to true (so we're not executing the router.visit again)
  3. If the component is remounted (but the page hasn't been refreshed), the router wont be triggered again due to the if statement wrapped around the router.visit in your onMounted code

End result would be, the code no longer triggering your router.visit when the component is remounted

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.