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

feat: add error-boundary #100

Merged
merged 15 commits into from
Dec 29, 2024
Merged

feat: add error-boundary #100

merged 15 commits into from
Dec 29, 2024

Conversation

atellmer
Copy link
Owner

#91

@atellmer atellmer added the enhancement New feature or request label Dec 27, 2024
@atellmer atellmer self-assigned this Dec 27, 2024
@atellmer
Copy link
Owner Author

atellmer commented Dec 27, 2024

working example

import { component, useState, ErrorBoundary, useMemo, Suspense } from '@dark-engine/core';
import { createRoot } from '@dark-engine/platform-browser';
import { DataClient, DataClientProvider, InMemoryCache, useApi as $useApi, useQuery } from '@dark-engine/data';

type Api = {
  fetchData: () => Promise<string>;
};

let count = 0;

const api: Api = {
  fetchData: () => {
    return new Promise((resolve, reject) => {
      console.log('fetch:start');
      setTimeout(() => {
        console.log('fetch:end');
        count++;
        if (count > 2) {
          resolve('Hello!');
        } else {
          reject('Network trouble');
        }
      }, 1000);
    });
  },
};

const useApi = () => $useApi<Api>();

const DataLoader = component(() => {
  const api = useApi();
  const { data } = useQuery('fetch-items', api.fetchData);

  return <div>data: {data}</div>;
});

const App = component(() => {
  const client = useMemo(() => new DataClient({ api, cache: new InMemoryCache() }), []);

  return (
    <DataClientProvider client={client}>
      <ErrorBoundary renderFallback={x => <Fallback {...x} />}>
        <Suspense fallback={<div>LOADING...</div>}>
          <DataLoader />
        </Suspense>
      </ErrorBoundary>
    </DataClientProvider>
  );
});

type FallbackProps = {
  error: Error;
  reset: () => void;
};

const Fallback = component<FallbackProps>(({ error, reset }) => {
  return (
    <>
      <div>Error!</div>
      <pre>{error.stack}</pre>
      <button onClick={reset}>refetch</button>
    </>
  );
});

createRoot(document.getElementById('root')).render(<App />);

@atellmer
Copy link
Owner Author

It needs some tests

@atellmer atellmer merged commit 7e7b2a1 into development Dec 29, 2024
1 check passed
@atellmer atellmer deleted the feat/boundary branch December 29, 2024 07:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant