react component load 5 times 'undefined' then it finds the inner html div

850 Views Asked by At

emphasized text

import React, { useState, useEffect,useRef } from "react";
import Axios from "./axios.js";


//ADblockerdetection
export  function Adblockerdetection() {
    const [firstname, setfirstname] = useState('');

    const [adblock, adblocdetected] = useState(false);

 Axios.get("/user").then((result) => {
       setfirstname(
       result.data.firstname
           );
         }); 

    useEffect(() => {
        return Adblockerdetection();
    });
  
 
    function Adblockerdetection() {
        const head = document.getElementsByTagName("head")[0];

        const noadblock = () => {
            adblocdetected(false);
        };

        const adblocker = () => {
            adblocdetected(true);
        };

        const script = document.createElement("script");
        script.id = "adblock-detection";
        script.type = "text/javascript";
        script.src = "./public/gpt.js";
        script.onload = noadblock;
        script.onerror = adblocker;
        head.appendChild(script);

        //this.adblocdetected() = this.adblocdetected().bind(this);
    }
    return (
        <div>
           
            <div className="AdblockerMessage">
                {adblock ? (<div className="modal1">
                    <div id="adblock_message" >
                        <h2>HELLO {firstname}</h2>
                        <p>it looks like you are using an Adblocker. <br/>Please disable
                        the adblocker for this page!</p>
                        <button
                            onClick={() => {
                                Adblockerdetection( window.location.reload(true));
                            }}
                        >
                          
                        try to proof of Adblocker
                        </button>
                    </div>
                    </div>
                ) : (
                   null
                )}
           
            </div>
        </div>
    );
}


export default function Adinjection(props) {
    const { adtype, zoneid, id, name } = props;
        var therealURL =
        "https://marcpassenheim.net/AdServerTest/www/delivery/afr.php?";
    var theRandom = Math.floor(Math.random() * 1000000 + 1);
    var urlparam = {
        zoneid: zoneid,
        cb: theRandom,
    };
    var theURL = Object.keys(urlparam)
        .map((key) => key + "=" + urlparam[key])
        .join("&");
    //the adurl
    var construUrl = therealURL + theURL;
//------USEstat--------------------------------------------


//----------------------------------------

    const ads = {
        bigsky: {
            id: id,
            name: name,
            src: construUrl,
            width: "160" + "px",
            height: "600" + "px",
        },
        sky: {
            id: id,
            name: name,
            src: construUrl,
            width: "120" + "px",
            height: "600" + "px",
        },

        billboard: {
            id: id,
            name: name,
            src: construUrl,
            width: "800" + "px",
            height: "250" + "px",
        },
        bigbillboard: {
            id: id,
            name: name,
            src: construUrl,
            width: "970" + "px",
            height: "250" + "px",
        },
        mediumrectangle: {
            id: id,
            name: name,
            src: construUrl,
            width: "300" + "px",
            height: "250" + "px",
        },
        hpa: {
            id: id,
            name: name,
            src: construUrl,
            width: "300" + "px",
            height: "600" + "px",
        },
    };
    //Component where the ADTYPE prop is overgiven
    const currentAd = ads[adtype];

 //----------------HIDETheSpots-------------------------
const [visible, setAdSpotvisible] = useState(false);

 useEffect( () => {
  
      return setAdSpotvisible(true);
 }, []);

//setthecomponent to display:none when its not loaded
const divStyleNone = {
 display: "none !important",
 height:0+'px !important',
 width:0+'px !important'
};
const divstyleBlock = {
 display: "block",
 background: "yellow",
 height:'auto',
 width:'auto'
 
};



const [iframe,stateiframe] =useState(<iframe/>)
const containerToProof = useRef()

const isEmpty = containerToProof.current;
if(isEmpty==='undefined'){
       console.log('allo')
}
useEffect(()=>{
    console.log('saysomething',isEmpty)   
    },[<iframe/>]);


    return (
        <div>
           <div  ref={containerToProof}  >

               {visible ? (<div style={divstyleBlock}>
                            <iframe
                                id={currentAd.id}
                                name={currentAd.name}
                                src={currentAd.src}
                                frameBorder="no"
                                scrolling="no"
                                width={currentAd.width}
                                height={currentAd.height}
                                allow="autoplay"
                               
                                
                            />
                        </div>):( <div style={divStyleNone}> </div>)
              
              
              
               }
        </div>
        </div>
    );







    
}

hi im trying to to proof the response of an adserver. To check which typeof response it is im using useRef() and the reference on the div where the iframe will be constructed and send the get request to the adserverhttps://i.stack.imgur.com/3kvMo.png

the ads object looks like :

https://i.stack.imgur.com/fe3aL.png

everytime im refresh the page the console.log statement 'saysomething' gives me 5 times an undefined and then it finds the divs. https://i.stack.imgur.com/2V5bX.png

5adinjection.js:171 saysomething undefined
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​


The problem is i need the innerHTML Value immediately to work with the stored value otherwise, when im trying to go on in an if statement or something different the console say 'can't find value of undefined blah blah....' Did i missed something im stuck here for hour s and need help.

1

There are 1 best solutions below

17
Jagrati On

It seems like you have to run Adblockerdetection() only after the first mount. For this you need to pass empty array to useEffect dependency. Also async functions should be inside useEffect.

    useEffect(() => {
       Axios.get("/user").then(result => {
          setfirstname(result.data.firstname);
       });
       return Adblockerdetection();
     }, []);

Also you are getting undefined because the value of containerToProof.current is assigned only once to isEmpty variable. So instead of doing console.log('saysomething',isEmpty) change to console.log('saysomething',containerToProof.current) inside useEffect.

useEffect(()=>{
    console.log('saysomething',containerToProof.current)   
 },[<iframe/>]);

To check if iframe is loaded

<div ref={containerToProof}>
          {visible ? (
            <div style={divstyleBlock}>
              <iframe
                id={currentAd.id}
                name={currentAd.name}
                src={currentAd.src}
                frameBorder="no"
                scrolling="no"
                width={currentAd.width}
                height={currentAd.height}
                allow="autoplay"
                onLoad={() => {
                  // iframe is loaded now and here you can call the function
                }}
              />
            </div>
          ) : (
            <div style={divStyleNone}> </div>
          )}
        </div>