From fc07a039bb79cc7647b7ba7edee46e4f019093e0 Mon Sep 17 00:00:00 2001 From: Michael Hunteman Date: Wed, 27 Mar 2024 18:24:55 -0700 Subject: Use ref instead of state for previous party size --- src/components/RsvpForm.tsx | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/src/components/RsvpForm.tsx b/src/components/RsvpForm.tsx index a1e4fa8..a6e7036 100644 --- a/src/components/RsvpForm.tsx +++ b/src/components/RsvpForm.tsx @@ -12,7 +12,7 @@ import { import { useForm, Controller, useFieldArray } from 'react-hook-form'; import { useOutletContext } from 'react-router-dom'; import { useUpdateGuestMutation, Guest } from '../apiSlice'; -import { useState } from 'react'; +import { useRef } from 'react'; type FormValues = { id: number; @@ -31,7 +31,7 @@ type FormValues = { function RsvpForm() { const [updateGuest] = useUpdateGuestMutation(); const guest: Guest = useOutletContext(); - const [previousPartySize, setPreviousPartySize] = useState(1); + const previousPartySize = useRef(0); const { register, @@ -62,21 +62,25 @@ function RsvpForm() { const handleParty = () => { const partySize = Number(watch('partySize')); - if (partySize > previousPartySize && partySize > 1 && partySize < 10) { + if ( + partySize > previousPartySize.current && + partySize > 1 && + partySize < 10 + ) { append( - new Array(partySize - previousPartySize).fill({ + new Array(partySize - previousPartySize.current).fill({ firstName: '', lastName: '', }) ); - setPreviousPartySize(partySize); - } else if (partySize < previousPartySize && partySize > 0) { + previousPartySize.current = partySize; + } else if (partySize < previousPartySize.current && partySize > 0) { remove( - [...Array(previousPartySize - partySize).keys()].map( + [...Array(previousPartySize.current - partySize).keys()].map( (_, i) => partySize - 1 + i ) ); - setPreviousPartySize(partySize); + previousPartySize.current = partySize; } }; -- cgit v1.2.3