Considering this bit of code, I would like to be able to add values to the correct state using the same function to avoid code duplications. How can I concatenate strings to get the correct variable and function names?
const [questionsAdditionalProperties, setQuestionsAdditionalProperties] = useState([]);
const [usersAdditionalProperties, setUsersAdditionalProperties] = useState([]);
const handleAddAdditionalProperty = (type) => {
//how to concatenate this valiable name to access the value in state?
const key = ${type}AdditionalProperties.length;
let newAdditionalProperty = [];
newAdditionalProperty.push(
// how to concatenate the function name to call the correct hook?
getQuestionsAdditionalPropertiesRow(type, key)
);
// how to concatenate the function name to call the correct hook and the variable name to use spread?
setQuestionsAdditionalProperties([...questionsAdditionalProperties, ...newAdditionalProperty]);
};
<p className="right" onClick={e => handleAddAdditionalProperty("questions")}><Button variant="primary" >Add Question Additional Property</Button></p>
<p className="right" onClick={e => handleAddAdditionalProperty("users")}><Button variant="primary" >Add Users Additional Property</Button></p>
I don't want to use objects as this will lead me to refactor too much code in this application.