How to use UseEffect and pass data to return statement in the react native

Viewed 81

Below is the return statement of abc.tsx

return (
<ImageBackground
  source={require("../assets/images/abc.png")}
  style={styles.bg}
>
    <CardStack>
      {
         byTest(globalThis.test).map((item) => (
          <Card key={item.id}>
            <CardItemForSwiper
              image={item.image}
              name={item.name}
              description={item.description}
            />
          </Card>
        )
        )
      }
    </CardStack>
</ImageBackground>
);

If you observe the above statement, we have something called byTest(globalThis.test) which is responsible to get an array of data from some other ts file and it looks like below

export const byTest = (test: string) => {

const filData = data.filter((rawData) => {
    return rawData.test== test
})
if (filData.length > 0) {
    globalThis.test= test
}
return new Promise((resolve)=>{return resolve(filData)})
}

Problem:

Now my problem is, byTest(globalThis.test) call is getting triggered multiple times because of multiple renders... so I have decided to use useEffect to get the data and pass it to this return.

So could you please help me with the best possible solution for this? Not just useEffect, as I am new to react Native I am looking for the best possible solution if useEffect hook doesn't fit

Goal: byTest(globalThis.test) call should be triggered only once even if we have multiple renders by abc.tsx

1 Answers

You can use useEffect to unsubscribe on success here. Here is an example I have used for user authorization that will help you:

useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged(user => {
        if(user) {
            navigation.replace("LoginScreen")
        }
    })
        return unsubscribe
    }, [])

Using useEffect here would be ideal on change of your state. unsubscribe upon the state. When your function returns the array of data, you can unsubscribe to it, so it does not render multiple times.

Official docs on useEffect that may offer further help!

Related