hernandeΩ
hernandeΩ

Reputation: 89

React HOC query graphql

I need to query graphql in multiple pages in my app and I am trying to create a react higher order function to do so.

This is the original:

const Profiles = () => {
  // Omitted code
  const { loading, error, data, refetch, fetchMore } = useQuery(
    GET_PROFILES(),
    {
      variables: { id },
    }
  );

  if (loading) {
    return <Loading />;
  }

  if (error) {
    // I need to find a way to eliminate this line because I am duplicating it on every page of my app
    if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
      return <Redirect to="/login" />;
    }

    return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
  }

  return (
    <div>OMITTED</div>
  );
};

And this is what I currently have:

const WithQuery = (Comp, query, getVariables) => (props) => {
  const { loading, error, data, refetch, fetchMore } = useQuery(
    query(),
    {
      variables: getVariables(),
    }
  )

  if (loading) {
    return <Loading />;
  }

  if (error) {
    // I need to find a way to eliminate this line because I am duplicating it on every page of my app
    if (error.message === '403: Forbidden' || error.message === '401: Unauthorized') {
      return <Redirect to="/login" />;
    }

    return <Alert message="Error" description="Failed to load profiles." type="error" showIcon />;
  }

  return <Comp {...props} />
}

const Profiles = WithQuery(() => {
  return (
   const {id} - useContext(UserContext);
    <div>OMITTED</div>
  );
}, GET_PROFILES, () => ({ id }));

I am getting an error because of this }, GET_PROFILES, () => ({ id })); line id cannot be found. How can I send the hoc the id prop and also, how can I access data from the query inside of the div to be displayed?

Upvotes: 0

Views: 175

Answers (1)

suddjian
suddjian

Reputation: 2406

id isn't defined because it only exists in the context of your anonymous function component (the first argument to WithQuery. It can only be used inside the function in which it is defined.

You can actually use hooks in your getVariables() function, so it should be fixable by moving the const {id} = useContext(UserContext) line into the () => ({ id }) function.

Upvotes: 1

Related Questions