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:
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?
CodePudding user response:
Contexte.Provider accept a value
props,
And should be used like:
<ParamsContext.Provider value={{selected, setSelected, textName, valueName}}>
<\ParamsContext.Provider>
CodePudding user response:
Provider accept a value prop, in your case, an object. So it should be:
<ParamsContext.Provider
value={{
selected,
setSelected,
textName,
valueName
}}
>
<InputsList />
</ParamsContext.Provider>