0

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.

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

It's a way to convert the value into its boolean representation, it's called double-bang operator. So truthy values equal to true and rest will be false. You can even omit the !! and the condition will work, but in my opinion, it makes things more readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.