@@ -3,7 +3,7 @@ import dynamic from 'next/dynamic';
33import Head from 'next/head' ;
44import { useRouter } from 'next/router' ;
55import { filter } from 'lodash' ;
6- import { Controller , useForm } from 'react-hook-form' ;
6+ import { Controller , useForm , useWatch } from 'react-hook-form' ;
77import { StringParam , useQueryParam } from 'use-query-params' ;
88import { z } from 'zod' ;
99import { zodResolver } from '@hookform/resolvers/zod' ;
@@ -191,7 +191,7 @@ function Mapping({ input }: { input: Input }) {
191191 const { data : sources } = useSources ( ) ;
192192 const [ dashboardId ] = useQueryParam ( 'dashboardId' , StringParam ) ;
193193
194- const { handleSubmit, getFieldState, control, setValue, watch } =
194+ const { handleSubmit, getFieldState, control, setValue } =
195195 useForm < SourceResolutionFormValues > ( {
196196 resolver : zodResolver ( SourceResolutionForm ) ,
197197 defaultValues : {
@@ -226,16 +226,24 @@ function Mapping({ input }: { input: Input }) {
226226 } , [ setValue , sources , input ] ) ;
227227
228228 const isUpdatingRef = useRef ( false ) ;
229- watch ( ( a , { name } ) => {
229+ const sourceMappings = useWatch ( { control, name : 'sourceMappings' } ) ;
230+ const prevSourceMappingsRef = useRef ( sourceMappings ) ;
231+
232+ useEffect ( ( ) => {
230233 if ( isUpdatingRef . current ) return ;
231- if ( ! a . sourceMappings || ! input . tiles ) return ;
232- const [ , inputIdx ] = name ?. split ( '.' ) || [ ] ;
233- if ( ! inputIdx ) return ;
234+ if ( ! sourceMappings || ! input . tiles ) return ;
235+
236+ // Find which mapping changed
237+ const changedIdx = sourceMappings . findIndex (
238+ ( mapping , idx ) => mapping !== prevSourceMappingsRef . current ?. [ idx ] ,
239+ ) ;
240+ if ( changedIdx === - 1 ) return ;
234241
235- const idx = Number ( inputIdx ) ;
236- const inputTile = input . tiles [ idx ] ;
242+ prevSourceMappingsRef . current = sourceMappings ;
243+
244+ const inputTile = input . tiles [ changedIdx ] ;
237245 if ( ! inputTile ) return ;
238- const sourceId = a . sourceMappings [ idx ] ?? '' ;
246+ const sourceId = sourceMappings [ changedIdx ] ?? '' ;
239247 const keysForTilesWithMatchingSource = input . tiles
240248 . map ( ( tile , index ) => ( { ...tile , index } ) )
241249 . filter ( tile => tile . config . source === inputTile . config . source )
@@ -263,7 +271,7 @@ function Mapping({ input }: { input: Input }) {
263271 }
264272
265273 isUpdatingRef . current = false ;
266- } ) ;
274+ } , [ sourceMappings , input . tiles , input . filters , getFieldState , setValue ] ) ;
267275
268276 const createDashboard = useCreateDashboard ( ) ;
269277 const updateDashboard = useUpdateDashboard ( ) ;
0 commit comments