0

I am making a simple get request in React like the following:

function App() {
  const [req, setReq] = useState();


  const getBasic = () => {
    axios
      .get(
        "https://financialmodelingprep.com/api/v4/price-target?symbol=AAPL&apikey=********"
          )
          .then((result) => setReq(result));

      };


     useEffect(() => {
       getBasic();
     }, []);
    
     console.log(req);
    
  return (
    <div>
    </div>
  );
}

The above code logs the same thing four times in the console. Was not sure if moving the console.log(req) into the return would do anything different, like:

 return (
        <div>
         {console.log(req)}
        </div>
      );

It did not however and had the same result.

I tried to do the same code but with async await syntax:

function App() {
  const [req, setReq] = useState();
  const getBasic = async () => {
    const getReq = await axios.get(
      "https://financialmodelingprep.com/api/v4/price-target?symbol=AAPL&apikey=**********"
    );

    setReq(getReq);
  };

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

  console.log(req);

  return (
    <div>
    </div>
  );
}

Still the same, getting four seperate console.log(req)'s in console.

The last thing I tried was using a onClick button instead of useEffect to make a request

return(
  <div>
    <button onClick={getBasic} />
  </div>
)

this results into two logs per click instead of four with useEffect.

I do not understand if in these instances I am making two or four requests or if I am still only making one request but it is logging multiple times, I would like to know why this is happening and what I should do to fix it, even though I can do the rest of my project with it working this way it appears I am not doing it optimally either way.

Caleb
  • 439
  • 8
  • 29
  • 1
    In the normal case, that would log `req` twice: Once at the outset with `undefined` (the default from `useState`), and then again after the state is set. If you're seeing four, I suspect you're using `StrictMode`, which will run your component twice (and thus do both of those logs twice, each). – T.J. Crowder Aug 08 '22 at 17:52
  • Ah I am running strict mode as it turns out, That makes sense why there are four then however with two being logged, shouldn't one be undefined? But they are both the same and they are both the request. Also to clarify, the request still is only being made one time right? – Caleb Aug 08 '22 at 17:55
  • Right, the request will be made once when the component mounts. There will be four `console.log`s (with StrictMode): `undefined`, the result from axios, `undefined`, and the result from axios. Without `StrictMode` it would just be `undefined` and then the result from axios. – T.J. Crowder Aug 09 '22 at 07:12

1 Answers1

1

Disable Strict Mode by deleting Strict Mode tags in index.js

Nemanja Jovic
  • 81
  • 1
  • 6