reactjs - update useFieldArray fields when index changes - Stack Overflow

admin2025-04-29  2

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?

Share Improve this question edited Jan 6 at 23:40 Ken White 126k15 gold badges236 silver badges466 bronze badges asked Jan 6 at 22:57 Milton JoséMilton José 531 silver badge6 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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!!!

转载请注明原文地址:http://www.anycun.com/QandA/1745940305a91410.html