3

I am trying to integrate an authenticated data provider into React-Admin but I am having trouble when the data provider does not yet have a valid auth token from the auth provider.

I am using https://github.com/des-des/ra-postgraphile-client

My code to instantiate the data provider looks like this:

const dataProvider = buildPostgraphileProvider({
  apolloHttpLinkOptions: {
    uri: `http://localhost:5433/graphql`,
    fetch: (url, options) => {
      // You can add custom auth logic with a wrapper around fetch
      const token = localStorage.getItem("token");

      if (!token) {
        return;
      }
      if (jwt.decode(token).exp < Date.now()) {
        localStorage.removeItem("token");
        return;
      }

      const headers = {
        ...options.headers,
        authorization: `bearer ${token}`
      };
      return fetch(url, { ...options, headers });
    }
  }
});
console.log(dataProvider);

I expected when React-Admin received an error from the data provider, it would redirect back to the homepage. But instead it throws an unhandled rejection.

Unhandled Rejection (Error): Network error: Cannot read property 'then' of undefined
new ApolloError
src/errors/ApolloError.ts:46
  43 | // Constructs an instance of ApolloError given a GraphQLError
  44 | // or a network error. Note that one of these has to be a valid
  45 | // value or the constructed error will be meaningless.
> 46 | constructor({
     | ^  47 |   graphQLErrors,
  48 |   networkError,
  49 |   errorMessage,

I also tried to return a HTTPError when no token is present:

return new HttpError("denied", 403, { status: 403 });

And got a different result:

Unhandled Rejection (Error): Network error: fetcher(...).then is not a function

reaaaaact
  • 31
  • 1

0 Answers0