I've created a React app using OpenWeather Maps. I'm having problems getting the API key to work. If I store it in the functional component, it works. But if I try to put it in a .env file and then import it, it won't load. It shows up in the fetch call as undefined.
export const Weather = () => {
const [weather, setWeather] = useState({})
const API = process.env.REACT_APP_WEATHER_KEY
const { coords, isGeolocationAvailable, isGeolocationEnabled } =
useGeolocated({
positionOptions: {
enableHighAccuracy: false,
},
userDecisionTimeout: 5000,
});
useEffect(() => {
if (coords) {
getWeather(coords, API).then(setWeather)
}
}, [coords])
return !isGeolocationAvailable ? (
<div>Your browser does not support Geolocation</div>
) : !isGeolocationEnabled ? (
<div>Geolocation is not enabled</div>
) : coords ? (
<React.Fragment>
<p>asdfasdfasdf</p>
<div> Today in {weather?.name}
<p>Current: {Math.round(weather?.main?.temp)}°F</p>
) : (
<div>Getting the location data… </div>
);
}
.ENV LOOKS LIKE THIS
REACT_APP_WEATHER_KEY = "(API here)"
FETCH CALL LOOKS LIKE THIS
export const getWeather = (coords, API) => {
return fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${coords.latitude}&lon=${coords.longitude}&units=imperial&appid=${API}`)
.then(res => res.json())
}
CodePudding user response:
I am an idiot. I had something else running. Shut down everything and restarted and appears to be working now. Thanks @AndyRay
CodePudding user response:
If you are making change to an .env
file, it doesn't reflect directly in the running application. You need to close or terminate the application and again start the application using npm start
.
CodePudding user response:
Try without the quotes meant as in:
REACT_APP_WEATHER_KEY=blahblahblah
Quotes are generally not required