Home > Software design >  How to re run a processing in React Native?
How to re run a processing in React Native?

Time:01-26

I'm developing a React Native application using hooks.

  React.useEffect(() => {
    
    // My processing I want to run every time I came into the component 
    Services.getDataFromEndPoint(url)
      .then((state) => {
        setOrdersData(state.data.rows);
        setLoading(false);
      })
      .catch((err) => {
        console.log("Error [PaidOrders] :", err);
      });

  }, []);

In this exemple, I am using useEffet but it runs the processing only one time. Is there a solution to run it every time we come into this screen ?

Thank you,

CodePudding user response:

I just found a solution, I had to add a listener with 'focus' value :

 React.useEffect(() => {
    getPaidOrder();
    const unsubscribe = navigation.addListener("focus", (e) => {
      getPaidOrder();
    });

    return unsubscribe;
  }, []);

CodePudding user response:

You need to also remove focus listener when unmounting.

  React.useEffect(() => {
    getPaidOrder();
    const unsubscribe = navigation.addListener("focus", (e) => {
      getPaidOrder();
    });

    return () => {
      unsubscribe();
      navigation.removeListener("focus", (e) => {
        getPaidOrder();
    });
   };
  }, []);

Alternatively, I would suggest using useFocusEffect. Then you will not need to duplicate addListener, removeListener everytime you need to detect if the screen is focused or not.

  •  Tags:  
  • Related