I am trying to put the OpenWeatherMap API Key in the .env file but when I call it, it console log a 401 error (Unauthorized), and when I do call it without the .env file directly in the app.js file it works perfectly.
App.js:
const [currentWeather, setCurrentWeather] = useState(null);
const [forecast, setForecast] = useState(null);
const handleOnSearchChange = (searchData) => {
const [lat, lon] = searchData.value.split(" ");
const currentWeatherFetch = fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_SECRET_KEY}`
);
const forecastFetch = fetch(
`https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_SECRET_KEY}`
);
Promise.all([currentWeatherFetch, forecastFetch])
.then(async (response) => {
const weatherResponse = await response[0].json();
const forecastResponse = await response[1].json();
setCurrentWeather({ city: searchData.label, ...weatherResponse });
setForecast({ city: searchData.label, ...forecastResponse });
})
.catch(console.log);
};
console.log(currentWeather);
console.log(forecast);
.env:
REACT_APP_SECRET_KEY = "199023c4fb4dc2be4f6ae2b9d23f12bd";