Home > Net >  React UseEffect hook firing every time I click on table row - Need a better way to handle this
React UseEffect hook firing every time I click on table row - Need a better way to handle this

Time:11-10

Hear me out, I have a table where if a row is clicked on, it will set the state and a modal will pop up containing the information from that row.

    const [addressLine1, SetAddressLine1] = useState();
    const [addressLine2, SetAddressLine2] = useState();
    const [city, SetCity] = useState();
    const [province, SetProvince] = useState();
    const [postalCode, SetPostalcode] = useState();

const rowEvents = {
        onClick: (e, row) => {
            toggleTrueFalse(); //sets visibility of modal
            setModalInfo(row) //An additional state I use to add infoformation
            SetAddressLine1(row.AddressLine1);
            SetAddressLine2(row.AddressLine2);
            SetCity(row.City);
            SetProvince(row.Province);
            SetPostalcode(row.Postalcode);
        },
    };

I then have added the ability to edit this information on the modal and update the database.

Input example of where state gets updated with the new input value and calls the "updateSubmittedApplication" function onSubmit:

<Editable 
editText="Edit"
initialValue={addressLine1.toString()} 
isValueClickable
mode="inline"
validate={(value) => {if(value) return;}}
onValidated={(newValue) => {SetAddressLine1(newValue);}}
onSubmit={updateSubmittedApplication}
type="textfield"
/>

updateSubmittedApplication function with useEffect to call function when dependency changes. (The setSubmitted state is set for the table information) :

const updateSubmittedApplication = () => {
const id = modalInfo.Id;
const updatedSubmit = {AddressLine1: addressLine1, AddressLine2: addressLine2, City: city,
        Province: province, PostalCode: postalCode}

        if(addressLine1|| addressLine2 || city || province || postalCode) {
            axiosPrivate.put(`/updateapp/${id}`, updatedSubmit)
            .then((res) => {
                getSubmittedData();
                const latestSubmitInfo = [...submitted, updatedSubmit];
                setSubmitted(latestSubmitInfo);
                console.log(res.data);
            }); 
        } 
    };


useEffect(() => {

            updateSubmittedApplication();  

    }, [addressLine1, addressLine2, city, province, postalCode])

I understand the reason why the function fires every time I click a row as the state has changed on the dependencies right away. Is there a better way which I can handle this so that it does not fire on every click but instead only fires when the input is changed?

CodePudding user response:

You could use some extra state isDirty.

Set it to false when you are copying a row's state into your local state. Set it to true in the input onChange.

Then you should be able to write if (isDirty) update(); in your effect.

  • Related