Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The error from useWeb3Context is of type Error, which doesn't have a code property - leads to TypeScript warning #32

Closed
pcowgill opened this issue Oct 21, 2019 · 7 comments

Comments

@pcowgill
Copy link

When using useWeb3Context from web3-react in a TypeScript-flavored create-react-app app, this error is shown: Property 'code' does not exist on type 'Error'. ts(2339)

Here's a snippet to reproduce it:

import { useWeb3Context, Connectors } from "web3-react";
const { Connector } = Connectors;

const { error } = useWeb3Context();

const blockRender =
    error &&
    error.code &&
    error.code === Connector.errorCodes.UNSUPPORTED_NETWORK;
@NoahZinsmeister
Copy link
Contributor

hey @pcowgill, thanks for the report!

makes sense, i override that error locally with this snippet: https://github.com/NoahZinsmeister/web3-react/blob/latest/src/declarations.ts#L20. looking at MDN though, it seems like name might be the right property for what i'm trying to accomplish: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/name.

i'm going to keep the issue open and experiment with this in the next version.

@pcowgill
Copy link
Author

@NoahZinsmeister Thanks for the example of how to override it! Agreed, I think name would suit your needs here.

@pcowgill
Copy link
Author

Also, you can subclass errors so that they’ll have name set automatically in the case of a frequently used “error code”

@NoahZinsmeister
Copy link
Contributor

🙏 that sounds perfect, i'll try that!

@pcowgill
Copy link
Author

@NoahZinsmeister In the meantime, do you know of any examples of an app using this library making use of those or similar declarations? Thanks!

@pcowgill
Copy link
Author

This seems to work for an app using this lib:

ErrorWithCode.ts

export interface ErrorWithCode extends Error {
  code?: string | number | undefined;
}

MyComponent.tsx

import { ErrorWithCode } from "[insert-path-here]/types/ErrorWithCode";
const {
    active,
    error,
    setConnector,
    setError
  }: {
    active: boolean;
    error?: ErrorWithCode | null;
    setConnector: any;
    setError: any;
  } = useWeb3Context();

(The any type for the functions isn't good TypeScript, but left it like that since that's not the focus here.)

@NoahZinsmeister
Copy link
Contributor

going to close this, as v6 uses custom errors which can be checked with instanceof! thanks for bringing this up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants