Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i want to load first element from api initially , but after making change to other user data the component goes back to first element data

//here i want to show first array data initially, but not on every state change or api call

useEffect(() => {
    data?.delivery_boys?.map((d, index) => {
      if (index === 0) {
        setDeliveryBoy(d);
      }
    });
    return () => {
      data;
    };
  }, [data]);

//here i am mutating data and setting state again

 const handleOnSubmit = () => {
    setAssignCustomerId(assignCustomerId);
    console.log(assignCustomerId, "assgnied ");
    toggleModal();
    const id = typeof deliveryBoy !== "undefined" && deliveryBoy.id;
    const params = { deliveryBoyId: id, assignCustomerId };
    assignCustomerMutation.mutate(params, {
      onSuccess: (data) => {
        setDeliveryBoy(data?.delivery_boy);
        queryClient.setQueryData([GET_DELIVERY_BOY_LIST.name, params], data);
        queryClient.invalidateQueries([GET_DELIVERY_BOY_LIST.name]);
      },
    });
  };

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think the line you want in the useEffect is to only set it if there is no deliveryBoy.

useEffect(() => {
    if (!deliveryBoy){
      // your code
    }

  }, [data]);

However in the useEffect i dont think you need to map over all the items either, so you can rewrite it like this:

useEffect(() => {
    if (!deliveryBoy) {
      setDeliveryBoy(data?.delivery_boys?.[0])  
    }
  }, [data]);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading