0

I am asking myself why I get the console log output twice when I open the web app. I dont feel I have to call twice the server if I only need to do it once. I cant figure out why this happens.

useEffect(() => {
        const myHeaders = new Headers();

        myHeaders.append('Content-Type', 'application/json');
        myHeaders.append('Authorization', 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJlcm5lc3RvZGVvcm96Y28iLCJyb2xlcyI6WyJST0xFX1VTRVIiXSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo1MDAwL2xvZ2luIiwiZXhwIjoxNjYyNTgxOTQ4fQ.uBwVEzLvdXHmbStCxgegDs-7dMBpnECf0T7AyRd6MjI');

        fetch('http://localhost:5000/org/activity/getallcategories', {
            method: 'GET',
            headers: myHeaders,
        })
            .then((response) => response.json())
            .then((data) => console.log(data)) //I see this output twice in the console
    }

    ,[])
  • Because with the new React 18, the useEffect will run twice in dev mode. [This stackoverflow question](https://stackoverflow.com/q/60618844/13329040) may explain it for you. – blurk Sep 09 '22 at 04:22
  • @blurk `useEffect` only runs twice in dev mode if you have enabled strict mode – smac89 Sep 09 '22 at 04:26
  • TL;DR `React.StrictMode` double mounts the component to ensure reusable state. Your code is missing a cleanup function to cancel in-flight fetch requests. See the answer [here](/a/73561625/8690857) for details. – Drew Reese Sep 09 '22 at 04:45

1 Answers1

0

StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).

For example, you might find that your {app} is wrapped by <React.StrictMode> in your index.js:

  ReactDOM.render(
     <React.StrictMode>
       {app}
     </React.StrictMode>,
    document.getElementById('root')
  );

If so, you can disable StrictMode by removing the <React.StrictMode> tag:

  ReactDOM.render(
    {app}
    document.getElementById('root')
  );
Bijay Poudel
  • 447
  • 6
  • 12
  • 3
    Please, no, don't suggest that ***removing*** the `StrictMode` component is the solution. It's there to help point out issues with your code for a reason. – Drew Reese Sep 09 '22 at 04:46