Reputation: 21
I create a context, use context in consumer, after update, the interface is not re-rendering. Please help.
The reason that I am not using state is because the Sample1
will have to pass down the component tree and it will be hard to maintain.
Another problem I am having is at onChange={updateContext}
. Is there a way to pass in some parameters into the updateContext
so that it knows which question and answer to be updated?
// Dependencies
import React, {useContext} from "react";
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
// CSS
import './App.css';
// API
import Sample1 from "./api/Sample1";
const UserContext = React.createContext();
function updateContext() {
console.log(Sample1);
Sample1.Questions[0].Answers[0].Selected = !Sample1.Questions[0].Answers[0].Selected;
}
function Selection(props) {
const userContext = useContext(UserContext);
return (
<UserContext.Consumer>
{() => (
<FormGroup row>
<FormControlLabel
control={<Checkbox checked={userContext.Questions[0].Answers[0].Selected} onChange={updateContext} name="Answers0" />}
label={userContext.Questions[0].Answers[0].Answer}
/>
</FormGroup>
)}
</UserContext.Consumer>
);
}
function App(props) {
return (
<UserContext.Provider value={Sample1}>
<Selection>
</Selection>
</UserContext.Provider>
);
}
export default App;
Upvotes: 1
Views: 477
Reputation: 7523
The way your are updating state will not re-render component. Please try below solution.
const { useContext, setContext } = useContext(UserContext);
And while updating..
function updateContext() {
setContext('New Value Here')// new Logic : Update whatever your context value is
console.log(Sample1);
Sample1.Questions[0].Answers[0].Selected = !Sample1.Questions[0].Answers[0].Selected;
}
Upvotes: 1