1

I came up with this way of doing network operations with ApolloClient but the problem is that the code looks very ugly and difficult to read, considering I have to write dozens of queries like this, it becomes tiresome and unmaintainable.

I haven't found anything in the Apollo docs or the actual code to configure the timeout.

let query = gql`
  query ... {
}`;
let x = 0;
let timer = setTimeout(() => {
  if (x === 0) {
    console.log('error');
  }
  x = 1;
}, 3000);
ApolloClient.query({ query }).then(({data}) => {
  clearTimeout(timer);
  if (x === 0) {
    if (data.result) {
      console.log(data.result)
    } else {
      console.log('error');
    }
  }
}).catch((error) => {
  clearTimeout(timer);
  console.log('error')
});

Is there a better way of achieving the same result with less and simpler code?

Computer's Guy
  • 5,122
  • 8
  • 54
  • 74

1 Answers1

0

Turns out, you can override the method:

export async function query(request) {
  const options = {...this._opts};
  return new Promise((resolve, reject) => {
    setTimeout(() => reject('Network timed out'), 1e4); // 10 sec
    return this.applyMiddlewares({
      request,
      options
    }).then((rao) => {
      return this.fetchFromRemoteEndpoint.call(this, rao);
    }).then(response => this.applyAfterwares({
      response: response,
      options
    })).then(({response}) => (response).json()).then((payload) => {
      resolve(payload);
    }).catch((e) => {
      reject(e);
    });
  }).catch((e) => {
    console.log(e);
    return null;
  });
}
Computer's Guy
  • 5,122
  • 8
  • 54
  • 74