Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error when using react context – Cannot destructure property

i trying to using Context on my react app
but i got error:

Uncaught TypeError: Cannot destructure property 'selected' of 'Object(...)(...)' as it is undefined.

in my InputsList file
on this line:

const { selected, setSelected } = useContext(ParamsContext);

ParamsContext:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { createContext } from 'react';

export const ParamsContext = createContext({
    selected: [],
    setSelected: () => {},
    textName: null,
    valueName: null
});

InputParams:

    import React, { useState } from 'react';
import InputsList from './InputsList';
    import { ParamsContext } from './services/ParamsContext';
    
    function InputParams(props) {
        const [selected, setSelected] = useState([]);
        const textName = "test";
        const valueName = "test2";
    
    
        return (
            <div>
                <ParamsContext.Provider
                    selected={selected}
                    setSelected={setSelected}
                    textName={textName}
                    valueName={valueName}>
                    <InputsList />
                </ParamsContext.Provider>
            </div>
        );
    }
    export default InputParams;

InputsList:

    import React, { useContext } from 'react';
    import { ParamsContext } from './services/ParamsContext';
    
    function InputsList(props) {
        const { selected, setSelected } = useContext(ParamsContext);
        return (
            <div>
                {selected.length}
            </div>
        );
    }

export default InputsList;

what can i do?

>Solution :

Contexte.Provider accept a value props,
And should be used like:

<ParamsContext.Provider value={{selected, setSelected, textName, valueName}}>
<\ParamsContext.Provider>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading