Reputation: 1
I read the previous "useContext returns undefined" questions but none of them solved my problem. I'm building a weather app using nextJS, geolocation browser api and openweathermap api. I resolved all promises and stored its data into a state variable:
import React, { createContext, useState, useEffect } from 'react'
export const GlobalContext = createContext({})
export default function GlobalContextProvider({children}){
const [city, setCity] = useState("")
const [temperature, setTemperature] = useState(0)
const [weather, setWeather] = useState("")
const [humidity, setHumidity] = useState(0)
useEffect(()=>{
navigator.geolocation.getCurrentPosition(async(position)=>{
const { latitude, longitude } = position.coords
try{
const response = await fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${process.env.NEXT_PUBLIC_API_KEY}`)
const data = await response.json(response)
setCity(data.name)
setTemperature(data.main.temp - 273)
setWeather(data.weather[0].main)
setHumidity(data.main.humidity)
}catch(err){
console.log(err)
}
})
}, [])
I even put all of that data into th value attribute in my context provider component:
return(
<GlobalContext.Provider value={
setCity,
city,
temperature,
setTemperature,
weather,
setWeather,
humidity,
setHumidity
}>
{children}
</GlobalContext.Provider>
)
And then I call the useContext hook to retrieve the "city" state variable value in another component:
import React,{ useContext } from 'react'
import { GlobalContext } from '../../context/globalContext'
import styles from './index.module.scss'
export default function Header() {
const { city } = useContext(GlobalContext)
Every component is wrapped inside the context provider component. I don't get whats going wrong. I know it isnt something when I set the state of this variable and the api calls return all the data it was suposed to return. I dont have a clue about whats going wrong.
Upvotes: 0
Views: 430
Reputation: 251
Whenever using multiple values in the context api you have to enclose it as an object, so just change to
value = {{
setCity,
city,
temperature,
setTemperature,
weather,
setWeather,
humidity,
setHumidity
}} >
Upvotes: 1