DEV Community

Smriti Rastogi
Smriti Rastogi

Posted on

Issue with React Context

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 };
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Thanks in advance

Top comments (3)

The discussion has been locked. New comments can't be added.
The issue is solved
Collapse
 
smritirgi profile image
Smriti Rastogi
Collapse
 
erickayalarias profile image
erickayalarias • Edited

Why you put it in an array? This will work

value = { {temperature , setTemperature, pressure, setPressure} }

Collapse
 
smritirgi profile image
Smriti Rastogi

No this gives error .