I am getting error - Uncaught TypeError: Cannot destructure property 'temperature' of '(0 , react_WEBPACK_IMPORTED_MODULE_0_.useContext)(...)' as it is undefined at Settings (Settings.js:12:1)
userSettingContext.js
import React , {useState} from 'react';
import Settings from './Settings';
const settingContext = React.createContext();
function UserSettingContext() {
const [temperature ,setTemperature] = useState("Celsius");
const [pressure , setPressure] = useState("HectoPascal");
return (
// the component that provides the value
<settingContext.Provider value={{temperature : [temperature , setTemperature] ,
pressure: [pressure, setPressure]}}>
<Settings/>
</settingContext.Provider>
)
}
export {settingContext , UserSettingContext };
Settings.js
import React , {useContext, useState} from 'react';
import { Modal } from 'react-bootstrap';
import {settingContext} from './UserSettingContext.js';
import {FiSettings} from 'react-icons/fi';
import './Settings.css';
function Settings() {
const [show , setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const {temperature , pressure } = useContext(settingContext);
return (
<>
<FiSettings onClick={handleShow} />
<Modal show={show} onHide ={handleClose}>
<Modal.Header closeButton>
<Modal.Title>User Settings</Modal.Title>
</Modal.Header>
<Modal.Body>
<label className='temperature'> Temperature
Celsius <input type="checkbox" /> Fahrenheit
</label>
<label className='pressure'> Pressure
<input type="checkbox" />
</label>
</Modal.Body>
</Modal>
</>
)
}
export default Settings;
Thanks in advance
Top comments (3)
The issue is solved- https://www.reddit.com/r/reactjs/comments/ufr5fq/issues_with_usecontext_hook_in_react/?utm_medium=android_app&utm_source=share
Why you put it in an array? This will work
value = { {temperature , setTemperature, pressure, setPressure} }
No this gives error .