diff --git a/src/utils/environment.ts b/src/utils/environment.ts index 60dd21d865..084b843cf1 100644 --- a/src/utils/environment.ts +++ b/src/utils/environment.ts @@ -1,3 +1,7 @@ export function isNodeJS() { - return typeof process !== 'undefined' && process.release.name === 'node' + return typeof process !== 'undefined' && process.release && process.release.name === 'node' +} + +export function isReactNative() { + return typeof navigator != 'undefined' && navigator.product == 'ReactNative' } diff --git a/src/utils/fetch.ts b/src/utils/fetch.ts index 9acd1d12bd..d8b0e448b3 100644 --- a/src/utils/fetch.ts +++ b/src/utils/fetch.ts @@ -1,13 +1,12 @@ -import { isNodeJS } from './environment' +import { isNodeJS, isReactNative } from './environment' -// RN exposes global fetch -let fetch = global.fetch -let Headers = global.Headers -let Request = global.Request -let Response = global.Response +let fetch: typeof global.fetch +let Headers +let Request +let Response // NodeJS doesn't have fetch by default -if (!fetch && isNodeJS()) { +if (isNodeJS()) { // eslint-disable-next-line @typescript-eslint/no-var-requires const nodeFetch = require('node-fetch') @@ -15,6 +14,16 @@ if (!fetch && isNodeJS()) { Headers = nodeFetch.Headers Request = nodeFetch.Request Response = nodeFetch.Response +} else if (isReactNative()) { + fetch = global.fetch + Headers = global.Headers + Request = global.Request + Response = global.Response +} else { + fetch = window.fetch.bind(window) + Headers = window.Headers + Request = window.Request + Response = window.Response } export { fetch, Headers, Request, Response } diff --git a/src/utils/ws.ts b/src/utils/ws.ts index 5802ca4487..d2860a4a4d 100644 --- a/src/utils/ws.ts +++ b/src/utils/ws.ts @@ -1,14 +1,17 @@ -import { isNodeJS } from './environment' +import { isNodeJS, isReactNative } from './environment' -// RN exposes global WebSocket -let WebSocket = global.WebSocket +let WebSocket: typeof global.WebSocket // NodeJS doesn't have WebSocket by default -if (!WebSocket && isNodeJS()) { +if (isNodeJS()) { // eslint-disable-next-line @typescript-eslint/no-var-requires const nodeWebSocket = require('ws') WebSocket = nodeWebSocket +} else if (isReactNative()) { + WebSocket = global.WebSocket +} else { + WebSocket = window.WebSocket.bind(window) } export { WebSocket }