I have an object quiz, it has a list of questions, questions have properties.
I want to update a property called question
in object question
(i know poor naming convention), inside questions
without creating a separate instance of the selected question.
This is what I have so far (but it doesn't like the square bracket of selecting the particular question being edited):
onChange={(e) => setQuiz({ ...quiz, questions[quiz.questions.indexOf(selectedQuestion)].question: e.target.value })}
error:
Unexpected token, expected ","
img of syntax:
CodePudding user response:
Super compact one-liner:
onChange={e => setQuiz({ ...quiz, questions: quiz.questions.map(q => q === selectedQuestion ? { ...q, question: e.target.value } : q) })}
This piece of code is really way too compact and hard to read.
So I personally would extract it to a named function instead of inline it. One more thing, I always prefer the setState(prevState => newState)
updater pattern instead of setState(newState)
directly. It avoids stale closure problem.
function MyComponent(props) {
const handleChange = (e) => {
setQuiz((quiz) => {
const questions = quiz.questions.map((q) => {
if (q !== selectedQuestion) return q;
return { ...q, question: e.target.value };
});
return { ...quiz, questions };
})
};
/* ... */
return <input onChange={handleChange} />
}
CodePudding user response:
Can you check whether this one work or not? (I just tried to prevent from above errors)
onChange={(e) => {
const newQuestions = quiz.questions;
newQuestions[quiz.questions.indexOf(selectedQuestion)].question = e.target.value;
setQuiz({ ...quiz, questions: newQuestions });
}}