reactjstypescriptenvironment-variablesvite.env

Getting the api key as undefined


The following is the component in which I am trying to make the call, it is initial state, so I was just testing the API call, but after I set up the environment variable I am getting the api key as undefined...

Following is the whole component...

import { useEffect, useState } from "react";
import brick from "./assets/tamland.webp";
import BrickSays from "./BrickSays";
import { location } from "./helper";

const APP_KEY = import.meta.env.REACT_APP_API_KEY;
console.log(APP_KEY);

const WeatherData = () => {
  const weatherStackAPI = `http://api.weatherstack.com/current?access_key=${APP_KEY}&query=${location}`;
  console.log(weatherStackAPI);

  const [apiResponse, setResponse] = useState<unknown>();

  const fetchWeather = async () => {
    const promise: Response = await fetch(weatherStackAPI);
    const rawData: any = await promise.json();
    setResponse(rawData);
    console.log(rawData);
  };

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

  console.log(apiResponse);

  return (
    <>
      <BrickSays />
      <img src={brick} alt='I love lamp' height='500px' />
    </>
  );
};

export default WeatherData;

Following is the .env file;

REACT_APP_API_KEY = appkey

I tried with the .env file inside and outside the "src" folder but with no result, and I have used vite for project creation.

I am expecting to get the api key as a string atleast


Solution

  • If you're using vite for your project, then you should do

    const APP_KEY = import.meta.env.VITE_API_KEY
    

    Prepending your environment variable with REACT_APP is mostly applicable to a create-react-app project.

    Additionally, make sure your .env file is located at the root of your project and have the environment variable saved as:

    VITE_API_KEY=YOUR_API_KEY