skip to Main Content

I have a request to authenticate my web page on Salesforce Marketing Cloud, the authentication must made and store only once.

My Problem is, when I request to authenticate and get a code I am getting two request, 1st request is successful and the 2nd request is error.

Question why am I getting two request one useEffect on react js? is my component loaded twice?

Here is my code:

useEffect(() => {
    async function initialize() {
      const params = await getParamsFromUrl();
      if (params.code) {
        await getTokenAndSaveToSession(params.code);
        await fetchJourneyData(); // Renamed the function to make it clearer
      } else {
        console.log('There is no code in the params');
      }
    }

    initialize();
  }, []); // The empty dependency array ensures that the effect runs only once on mount

  async function getTokenAndSaveToSession(code: string) {
    try {
      const authService = new AuthService();
      const result = await authService.getToken(code);
      sessionStorage.setItem('token', result.token);
      sessionStorage.setItem('expiration', result.expiration.toString());
    } catch (error) {
      console.log(error);
    }
  }

2

Answers


  1. According to React docs, in development, React mounts your components twice to ensure that your component rendering is pure.

    React intentionally remounts your components in development to find bugs like in the last example. The right question isn’t “how to run an Effect once”, but “how to fix my Effect so that it works after remounting”.

    Usually, the answer is to implement the cleanup function. The cleanup function should stop or undo whatever the Effect was doing. The rule of thumb is that the user shouldn’t be able to distinguish between the Effect running once (as in production) and a setup → cleanup → setup sequence (as you’d see in development).

    For your case, if the server you are making a request to only allows request once, you may want to handle the case when your component makes the second request, so that it reuses the authentication code already obtained in the first request.

    Login or Signup to reply.
  2. Because you are using <StrictMode>.[react-docs] The result is that useEffect runs twice thereby making your api call twice. If you don’t not want these extra development checks, simply remove <StrictMode> (not advised) or control useEffect.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search