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

Failed to execute 'fetch' on 'Window': Illegal invocation #204

Open
Lonli-Lokli opened this issue Feb 25, 2025 · 0 comments
Open

Failed to execute 'fetch' on 'Window': Illegal invocation #204

Lonli-Lokli opened this issue Feb 25, 2025 · 0 comments

Comments

@Lonli-Lokli
Copy link

Lonli-Lokli commented Feb 25, 2025

Failed to execute 'fetch' on 'Window': Illegal invocation error happens when cross-fetch is passed as class field

Playground

Note: it will work with "cross-fetch": "3.0.4"

import { useEffect, useState } from 'react';
import reactLogo from './assets/react.svg';
import viteLogo from '/vite.svg';
import crossFetch from 'cross-fetch';
import './App.css';

type Fetcher = typeof crossFetch;

class MyFetcher {
  constructor(protected fetcher: Fetcher) {}

  run() {
    return this.fetcher('https://api.github.com/users/lquixada');
  }
}

const fetcher = new MyFetcher(crossFetch);

function App() {
  const [apiCall, setApiCall] = useState('');

  useEffect(() => {
    // React advises to declare the async function directly inside useEffect
    async function getUser() {
      try {
        const res = await fetcher.run();

        if (res.status >= 400) {
          setApiCall('Bad response from server');
          return;
        }

        const user = await res.json();
        setApiCall(JSON.stringify(user));
      } catch (err: any) {
        setApiCall('FAILED: ' + err.message);
      }
    }

    if (!apiCall) {
      getUser();
    }
  }, []);

  return (
    <>
      <div>
        <a href="https://vite.dev" target="_blank">
          <img src={viteLogo} className="logo" alt="Vite logo" />
        </a>
        <a href="https://react.dev" target="_blank">
          <img src={reactLogo} className="logo react" alt="React logo" />
        </a>
      </div>
      <h1>Vite + React</h1>
      <div className="card">
        <p>API call results: {apiCall}</p>
      </div>
      <p className="read-the-docs">
        Click on the Vite and React logos to learn more
      </p>
    </>
  );
}

export default App;
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

1 participant