Home > OS >  React Native: How to conditionally render a value returned from a function that calls Firebase funct
React Native: How to conditionally render a value returned from a function that calls Firebase funct

Time:05-18

In my React Native app, I have the following function that returns a value from Firebase:

const func = () => {
  const a = useFirestoreCollection(
    userRepository
      .getRef()
      .collection('collection1')
      .doc('doc1')
  )
  return a.name;
}

and then the component looks like this:

return (
  <Text>
    {func()}
  </Text>
)

The problem is, I want to render it conditionally, like this:

return (
  <Text>
    {func() ? func() : "backup"}
  </Text>
)

but this throws the error Rendered more hooks than during the previous render.

How can I achieve this conditional render?

CodePudding user response:

The code is already breaking the rules of hooks by calling useFirestoreCollection in a nested function so the use case isn't valid. Call useFirestoreCollection as a hook normally and check the returned value.

Example:

const a = useFirestoreCollection(
  userRepository
    .getRef()
    .collection('collection1')
    .doc('doc1')
);

...

return (
  <Text>
    {a?.name || "backup"}
  </Text>
);
  • Related