reactjsapi-hook

ReactJS How to fetch only if a condition is true?


I'm trying to find a proper way to use useFecthApi conditionnally.

I have the following component :

export const DetailedUser: FC = () => {
  const userState = useFetchApi(() => findUser(userId))

  const fetchContacts = mustFecthContacts() // implemenattion does not matter
  return (
    <>
       <UserInformation userState={userState } />
    </>
  )
}
type Props = Readonly<{
  userState: State<UserDetails>
}>

export const UserInformation : FC<Props> = ({ userState }) => {

}

What I would like to do, is to create a contactState defined by const contactState= useFetchApi(() => findContacts(userId)) only if fetchContacts equals true, and then pass this contactState to UserInformation.

So basically, something like :

export const DetailedUser: FC = () => {
  const userState = useFetchApi(() => findUser(userId))
  // fetchContacts is a boolean (implementation is not important)
  const fetchContacts = mustFecthContacts()

  const contactStates = fetchContacts ? useFetchApi(() => findContacts(userId)) : undefined
  return (
    <>
       <UserInformation userState={userState} contactsState = {contactStates } />
    </>
  )
}
type Props = Readonly<{
  userState: State<UserDetails>,
  contactStates? : State<ContactDetails>
}>

export const UserInformation : FC<Props> = ({ userState, contactStates }) => {

}

I'm pretty new to react (and to frond en development) so I don't know how to achieve that properly. Any advice ?

Thanks.


Solution

  • You should use useEffect hook to fetch data. And also useState to store the data locally in a component.

    Something like:

    // this stores the userState properly
    const [userState, setUserState] = useState(() => {
      return useFetchApi(() => findContacts(userId))
    });
    
    // this triggers everytime fetchContacts changes and will
    // fetch new data if fetchContacts is "truthy"
    useEffect(() => {
      if(!!fetchContacts) {
        const userData = useFetchApi(() => findContacts(userId))
        setUserState(userData)
      }
    }, [fetchContacts])