javascriptreactjsenvironment-variablesvite

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.

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