I have this simple code in NextJS:
const {
fields: alternatives,
append,
remove,
replace,
} = useFieldArray({
control,
name: `questions.${questionIndex}.alternatives`,
});
useEffect(() => {
console.log('alternatives updated')
}, [alternatives])
All I want is to update the alternatives array when questionIndex changes, and with that run the console.log inside useEffect hook. How is it possible?
I have this simple code in NextJS:
const {
fields: alternatives,
append,
remove,
replace,
} = useFieldArray({
control,
name: `questions.${questionIndex}.alternatives`,
});
useEffect(() => {
console.log('alternatives updated')
}, [alternatives])
All I want is to update the alternatives array when questionIndex changes, and with that run the console.log inside useEffect hook. How is it possible?
You need to add questionIndex in the useEffect dependency array. The reference to the alternatives array might not always update since useFieldArray relies on the same control instance.
useEffect(() => {
console.log('alternatives updated');
}, [alternatives, questionIndex]); // Add questionIndex here
Hope it helps!!!
