Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

UseEffect in infinite loop when using vite env variables

I have looked through the topic already discussed, but I am not finding an answer for my case anywhere. I have a function:

export async function onlyMyErrorsMatter(){
  try {
    // Simulate API call
    const response = await fetch('www.some-url.com', {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer invalid-token', // Simulate permission issue
      },
    });

    if (!response.ok) {
      console.error(`API Error: ${response.status} ${response.statusText}`);
      window.location.href = url; // Use the dynamic URL
     }

    }

    return await response.text();

  } catch (error) {
    console.error("Error caught in onlyMyErrorsMatter:", error);

    // Check if redirection is already done
    window.location.href = url; // Use the dynamic URL
  }
};

As you can see I use dynamic URL which comes from my env file which is provided by Vite:

const url = SOME_VITE_ENV_VAR

I have a react component, which I am using the data in.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function Component() {
  const [result, setResult] = useState("");

  useEffect(() => {
    const fetchResult = async () => {
      const result = await onlyMyErrorsMatter();
      if (result) {
        setResult(result);
      }
    };

    fetchData();
  }, []);

The problem is, when I end up at the endpoint which actually should fire an auth error and redirect, I get into the render loop, no redirect. When I however replace the url with a hardcoded one, like

const url = "www.example.com"

Loop disappears and all works as it should. But I need a dynamic URL here. Also it’s important errors are handled in the separate function, still I am only interested in redirects in special cases of API fetch problems, no other errors should fire a redirect.

Moreover, with dynamic urls my endpoint gets another addition of "/undefined", which is incredibly weird and I can’t really find where is it coming from. Seems like my env variable can be undefined? Is this causing the issue.

>Solution :

  1. Prefix env variable with VITE. i.e. VITE_SOME_KEY=123
  2. Try to load env variable like import.meta.env.VITE_SOME_KEY

enter image description here

Reference link: https://vitejs.dev/guide/env-and-mode

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading