Reputation: 151
I have two sibling components (A & B) that I'm trying to pass react context between. Not static context. The context is created and updated in component A like so:
export const ModelContext = React.createContext({ model: '' });
function Models() {
const [check, setCheck] = useState({});
const [alert, setAlert] = useState(false);
let model = useContext(ModelContext);
const handleChange = (event) => {
const arr = Object.keys(check);
if (arr.length === 1 && arr.includes(event.target.name) === false) {
setAlert(true);
} else if (arr.length === 1 && arr.includes(event.target.name) === true) {
setAlert(false);
setCheck({});
model = check;
console.log(model);
} else {
setCheck({ ...check, [event.target.name]: event.target.checked });
setAlert(false);
}
};
I update the context (ModelContext) in this component in the handleChange. I can see from the console.log(model) that the context is updating as I desire.
However, in component B the context (ModelContext) is not being updated. I'm not sure where to go from here. Here is component B:
import { ModelContext } from './index';
function Fields() {
const modelSelected = useContext(ModelContext);
}
Is it possible to update the context in this fashion or should I take another approach?
Upvotes: 0
Views: 1314
Reputation: 5064
What you are seeing in the console log is after updating the model object. It is no longer referring to the context. It has a new reference now after model=check
.
First of all, if you want to pass the context between 2 siblings, the common parent should be wrapped around with context providers. You can create a context provider component.
const ModelContext = useContext({model: ''});
const ContextProvider = ({children, modelData}) => {
const [model, setModel] = useState(modelData);
return <ModelContext.Provider value={{model, setModel}}>{children}</ModelContext.Provider>
}
const Parent = () => {
return (
<ContextProvider modelData={your model data}>
<Models />
<Fields/>
</ContextProvider>
)
}
const Models = () => {
const [check, setCheck] = useState({});
const [alert, setAlert] = useState(false);
const {model, setModel} = useContext(ModelContext);
const handleChange = (event) => {
const arr = Object.keys(check);
if (arr.length === 1 && arr.includes(event.target.name) === false) {
setAlert(true);
}
else if (arr.length === 1 && arr.includes(event.target.name)===true) {
setAlert(false);
setCheck({});
setModel(check);
console.log(model);
} else {
setCheck({ ...check, [event.target.name]: event.target.checked });
setAlert(false);
}
};
const Fields = () => {
const {model: modelSelected} = useContext(ModelContext);
console.log(modelSelected);
}
You have to do this because, the context doesn't automatically get to the siblings if you do not wrap their parent with the context provider. This blog might be helpful for you to understand the usage of context
Upvotes: 1