0

I am trying to find a better way to handle all of my survey data at once. Able to have the components controlled is a good idea but I dont know if it is good practice to try to control them this way or I am just approaching this the wrong way.

This is the way I am trying to structure the survey.

const [survey, setSurvey] = useState({
   questionOne: { question: '', a: '', b: '', c: '' },
   questionTwo: { question: '', a: '', b: '', c: '' },
   questionThree: { question: '', a: '', b: '', c: '' }
});

And this is the way that I am trying to handle the change:

const handleChange = (e, questionName) => {
  const { name, value } = e.target;
  console.log(questionName, name, value);
  setSurvey({
    ...survey,
    [questionName[name]]: value,
  });
};

If any ideas if this can be targeted correctly I would very much appreciate any tips. Thank you.

1 Answers1

1

I suggest you read this Should I use one or many state variables?

Generally, a better option is to break up a single, all-encompassing state into separate, smaller states. But splitting depends on whether your state contains multiple unrelated states. If the state represents one type of data model, you don't have to split it.

The setState returned by useState hook is a replace operation, not the merge operation similar to the this.setstate () method of class component.

Split into independent states, no longer use the spread operator(...) for the merge operation. Perform SET operations instead of MERGE operations make the code easier, more readable.

And you can use custom hooks packages related to state and logic. The custom hooks can give more meaningful names, which helps improve code readability

So your code can be refactored to:

const [questionOne, setQuestionOne] = useQuestionOne();
const [questionTwo, setQuestionTwo] = useQuestionTwo();
const [questionThree, setQuestionThree] = useQuestionThree();
function useQuestionOne() {
  const [questionOne, setQuestionOne] = useState({a: '', b: '', c: ''})
  // other logic, useEffect(), resetQuestionOne, etc...
  return [questionOne, setQuestionOne]
}
// other custom hooks...
Lin Du
  • 88,126
  • 95
  • 281
  • 483
  • Thank you. I started with the states all independent but I thought it was too repetitive. Now I see that creating a custom hook will be way more beneficial. – hunter motko Nov 18 '21 at 14:30