Search code examples
reactjstypescriptsingle-page-application

I cannot see an ad added by a script when I navigate from and back to a page in React


I have a small react app where I am supposed to add an ad. I have a script that loads the ads to the ins placeholders.

import { useEffect } from 'react';

function AdsComponent() {
    useEffect(() => {
        const script = document.createElement('script');
        script.src = 'https://example.example.net/js/code.min.js';
        script.async = true;
        script.setAttribute('data-cfasync', 'false');
        document.body.appendChild(script);

        return () => {
            document.body.removeChild(script);
        };
    }, []);

    return (
        <div className='mt-[2rem] mr-[2rem]'>
            <ins className='aso-zone' data-zone='96230'></ins>
            <ins className='aso-zone' data-zone='96231'></ins>
        </div>
    );
}

export default AdsComponent;

The problem : When I navigate to another page and back to the one with the ad. The ad does not show.
On initial page load or refresh

on initial page load

On navigating to another page and back:

enter image description here.

Is there a way to ensure that on navigating the ad is reloaded?


Solution

  • I found the problem to be with the ad service provider. I managed to solve the problem by caching the ad on inial load to session storage and using the cached version on subsequent rerenders