I have state variables in a React context
export const FormProvider = ({ children }) => {
const dispatch = useDispatch();
const loadedForm = useSelector((state) => state.forms.newForm);
const [title, setTitle] = useState(loadedForm.title);
const [description, setDescription] = useState(loadedForm.description);
const [questions, setQuestions] = useState(loadedForm.questions);
const [headerNotes, setHeaderNotes] = useState(loadedForm.headerNotes);
const [footerNotes, setFooterNotes] = useState(loadedForm.footerNotes);
useEffect(() => {
console.log("questions", questions);
}, [questions]);
useEffect(() => {
dispatch(
updateNewForm({
title,
description,
questions,
headerNotes,
footerNotes,
})
);
}, [title, description, questions, headerNotes, footerNotes, dispatch]);
return (
<FormContext.Provider
value={{
title,
setTitle,
description,
setDescription,
questions,
setQuestions,
headerNotes,
setHeaderNotes,
footerNotes,
setFooterNotes,
}}
>
{children}
</FormContext.Provider>
);
};
All variables are updating correctly when I use the setValue
except setQuestions
When I use setQuestions
, it will update if I change a property of one of the questions, such as question.id
. However, it does not update when I set the value to a different array.
I’m trying to delete a question using
const { questions, setQuestions } = useContext(FormContext);
function removeQuestion() {
let newQuestions = [...questions];
newQuestions = newQuestions.filter((q) => q.id !== question.id);
setQuestions(newQuestions);
}
But questions is not updating
Other functions are working though, like
function changeText(text) {
const newQuestions = [...questions];
newQuestions.find((q) => q.id === question.id).text = text;
setQuestions(newQuestions);
}
Any assistance is greatly appreciated!
I created another function in the context
const qs = (questions) => {
console.log("questions", questions);
setQuestions(questions);
};
When I use this inside the removeQuestion
function, it does print the correct array with the question removed, but questions
is not updating to the new value.