Is there any way to trigger a function when prefetfcing is done in Gatsby?

Viewed 43

I am quite new to front-end development and I am sorry if this is a damn question.

I am using Gatsby project to create my web site. In this web site, I have multiple pages and one of the pages adds content to an element after its page is created.

For this, I use something like below.

useEffect(() => {
    addView()
    return () => {
        console.log("unmounted");
    }
}, [])

This works as expected. However, addView() function takes a lot of time to load so I would like to preload this when users arrive the home page.

I assume I can achieve something like this by triggering addView() after gatsby prefetches the page instead of using useEffect(). But I am not sure how I can know when gatsby prefetch is done.

So my question is, is there any way to trigger a function when prefetch is done and a certain element is created in another page?

1 Answers

The tricky part of your addView() function is that you need the DOM tree to be rendered in order to populate your element, that's why the useEffect indeed.

Said that, you can check the Gatsby Browser APIs to see if there's anyone that fit's your requirements. However, in the gatsby-browser.js file you will be outside the React's lifecycle so it will be difficult to guess how the code will behave.

I don't know if it's an option for your use-case but the optimal solution would be to populate and fill (what addView() does) in Gatsby fetching methods.

Alternatively, you can try to trigger your addView() function only if the element is empty and removing the unmount:

useEffect(() => {
    if(element.current.length > 0){ // or any other validation like checking if it has children
       addView()
    }
}, [])

Assuming that you are using useRef hook (that's why the .current) to get the element to be filled. With this approach, you will only trigger the function once.

Related