From 9038775a418e50e2838be0b66c54f30e068a4696 Mon Sep 17 00:00:00 2001 From: Max Makaluk Date: Sun, 22 Dec 2024 20:51:28 +0200 Subject: [PATCH] fix(persons): fix random new speaker field #3136 --- .../speakers_list/useSpeakersList.tsx | 39 ++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/src/features/persons/speakers_catalog/other_congregations/speakers_list/useSpeakersList.tsx b/src/features/persons/speakers_catalog/other_congregations/speakers_list/useSpeakersList.tsx index 765f5ac506..24447c0f76 100644 --- a/src/features/persons/speakers_catalog/other_congregations/speakers_list/useSpeakersList.tsx +++ b/src/features/persons/speakers_catalog/other_congregations/speakers_list/useSpeakersList.tsx @@ -4,17 +4,54 @@ import { buildPersonFullname } from '@utils/common'; import { fullnameOptionState } from '@states/settings'; import { visitingSpeakersState } from '@states/visiting_speakers'; import { speakersCongregationsState } from '@states/speakers_congregations'; +import { useEffect, useRef, useState } from 'react'; const useSpeakersList = (cong_id: string, isEdit: boolean) => { const fullnameOption = useRecoilValue(fullnameOptionState); const visitingSpeakers = useRecoilValue(visitingSpeakersState); const congregations = useRecoilValue(speakersCongregationsState); + const [visitingSpeakersBuffer, setVisitingSpeakersBuffer] = + useState(visitingSpeakers); + + useEffect(() => { + const prevVisitingSpeakersBuffer = visitingSpeakersBufferRef.current; + + if (visitingSpeakers.length > prevVisitingSpeakersBuffer.length) { + const newSpeakers = visitingSpeakers.filter( + (speaker) => + !prevVisitingSpeakersBuffer.some( + (item) => item.person_uid === speaker.person_uid + ) + ); + + setVisitingSpeakersBuffer((prev) => [...prev, ...newSpeakers]); + return; + } + + const updatedSpeakers = prevVisitingSpeakersBuffer.map((bufferSpeaker) => { + const updatedSpeaker = visitingSpeakers.find( + (speaker) => + bufferSpeaker.person_uid === speaker.person_uid && + bufferSpeaker._deleted.value !== speaker._deleted.value + ); + return updatedSpeaker || bufferSpeaker; + }); + + setVisitingSpeakersBuffer(updatedSpeakers); + }, [visitingSpeakers]); + + const visitingSpeakersBufferRef = useRef(visitingSpeakersBuffer); + + useEffect(() => { + visitingSpeakersBufferRef.current = visitingSpeakersBuffer; + }, [visitingSpeakersBuffer]); + const congregation = congregations.find( (record) => record.id === cong_id && record._deleted.value === false ); - const filteredList = visitingSpeakers.filter( + const filteredList = visitingSpeakersBuffer.filter( (record) => record._deleted.value === false && record.speaker_data.cong_id === cong_id );