javascriptreactjsgoogle-chromemobile

window.onload Is not firing on mobile, while working on desktop. (react js)


Thank you for your time and without further ado, let's get to the topic:


I need to run 1 of 2 different functions based on the starting boolean. I'm using window.onload to determine which one to run. (in the original code those functions determine what to display on the page)

Everything works fine on a desktop browser, but unfortunately, this solution does not work on mobile.

I've broken up my bug into this code:

import "./App.css";
import React from "react";

function App() {
  var startBoolean = true;                // starting condition, will be changed "manually"

  window.onload = (event) => {
    onLoadFunction();
  };

  const onLoadFunction = () => {
    if (startBoolean === true) {
      functionOnTrue();
    }
    if (startBoolean === false) {
      functionOnFalse();
    }
  };

  const functionOnTrue = async () => {
    console.log("Runing functionOnTrue");
    alert("Runing functionOnTrue");
  };

  const functionOnFalse = async () => {
    console.log("Runing functionOnFalse");
    alert("Runing functionOnFalse");
  };

  return (
    <div className="App">
      <button onClick={onLoadFunction}>Test onLoadFunction</button>
    </div>
  );
}

export default App;

Working fine on a desktop, but not on a mobile. (alert is not popping up)To make it work you need to manually run the function, by pressing the "Test onLoadFunction" button.

Any idea why it's not running?

And yes, I'm new to React ;)


Solution

  • Thank you all, it worked. To sum it up:


    As some of you mentioned, the answer was as simple as switching from window.onloade to useEffect.

    From:

    window.onload = (event) => {
       onLoadFunction();
    };
    

    to:

     useEffect(() => {
        onLoadFunction();
     }, []);
    

    Though there are two things I feel are worth adding.

    1. To make it work, remember to add import React, {useEffect} from "react"; to the top of your file. or use react.useEffect.
    2. Chek if you don't have your strict mode enabled, it may cause your page to rerender twice. With might lead to some trouble. More here: link.