So I am working on a project, where a user would provide questions and at the time of applying, the applicant would provide responses to these questions.
Here is my array of the user’s questions
const [answers, setAnswers] = useState({}) questions = [ {id: 1, questionType: boolean, required: true, question: 'Are you a UK resident?'}, {id: 2, questionType: text, required: true, question: 'give brief description about you'}, {id: 3, questionType: text, required: false, question: 'How old are you'} ]
from this array, I’ve mapped each of them
{questions?.map((q) => ( <Box sx={{ py: 1 }} key={q.id}> <p>{q.question}</p> {q?.questionType === 'boolean' ? ( <Select id='location' required={q.required} onChange={(e) => setAnswers(e.target.value)} > <MenuItem value='Yes'>Yes</MenuItem> <MenuItem value='No'>No</MenuItem> </Select> ) : ( <OutlinedInput required id='name' type='text' onChange={(e) => setAnswers(e.target.value)} /> )}
The answer of the first one overrides the answer of the second one. How do i fix this?? SO i can persist all the answers.
Advertisement
Answer
You could for example use a Map which maps question IDs to answers to keep track of questions and the associated answers.
// map that stores an answer to a question ID // e.g. // 1 => Yes // 2 => I am a developer // 3 => 123 const [answers, setAnswers] = useState(new Map()); questions = [ { id: 1, questionType: boolean, required: true, question: "Are you a UK resident?", }, { id: 2, questionType: text, required: true, question: "give brief description about you", }, { id: 3, questionType: text, required: false, question: "How old are you" }, ];
Then have a function which updates the Map whenever a question is answered. This function takes the question ID and the value. It also has to create a new Map every time as React only does a shallow comparison and state should be treated as immutable.
function updateAnswer(id, value) { const newMap = new Map(answers); newMap.set(id, value); setAnswers(newMap); }
Then last but not least you need to call your update function.
{questions?.map((q) => ( <Box sx={{ py: 1 }} key={q.id}> <p>{q.question}</p> {q?.questionType === 'boolean' ? ( <Select id='location' required={q.required} onChange={(e) => updateAnswer(q.id, e.target.value)} > <MenuItem value='Yes'>Yes</MenuItem> <MenuItem value='No'>No</MenuItem> </Select> ) : ( <OutlinedInput required id='name' type='text' onChange={(e) => updateAnswer(q.id, e.target.value)} /> )}