I have a callback function that updates two states.
An example code is given below,
const [index, setIndex] = useState(-1);
const [fields, setFields] = useState([]);
const callbackFunction = () => {
setIndex(prevState => {
const newIndex = prevState + 1;
setFields(prevState => [...prevState, {id: newIndex, question: "", type: ""}]);
return newIndex;
});
};
//I will be calling the callbackFunction somewhere over here in my JSX
Please note that my initial description may not accurately describe the code. Apologies if so.
I want to know if the code I implemented is
The red flag for me is the state update within a state update.
Thanks in advance for any information that would enlighten me.
useState
.What you can do is:
const callbackFunction = () => {
const newIndex = index+ 1;
setIndex(newIndex);
setFields([...fields, {id: newIndex, question: "", type: ""}]);
};
This IMO way cleaner and pretty straight forward, no nested code, no additional callback function inside setState
and should work the same.
Simply do this
const [index, setIndex] = useState(-1);
const [fields, setFields] = useState([]);
const callbackFunction = () => {
const newIndex = index+ 1;
setIndex(prevState => newIndex);
setFields(prevState => [...prevState, {id: newIndex, question: "", type: ""}])
};
Your intention is clear why you try to update the setFeilds
inside the setIndex
. You want to get the updated index and pass it to the setFeilds
. Sure what your trying to do here is an anti-pattern. You could simply follow the above way to achieve what you want.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.