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

Only the first promise in the state variable has a rejection handler #324

Open
illright opened this issue Jun 1, 2021 · 0 comments
Open

Comments

@illright
Copy link

illright commented Jun 1, 2021

I have a state variable that holds a promise. On the click of a button, that promise is replaced with a new one (all of them are fetch requests). If the initial promise fails, the Async component helpers render the error just fine. If I click the button and the new promise fails, an Unhandled Rejection is thrown.

Here's the code that illustrates the problem:

import { useState } from 'react';
import Async from 'react-async';

async function getRandomNumber() {
  const res = await fetch(`https://svelte.dev/tutorial/random-number`);
  const text = await res.text();

  if (res.ok) {
    return text;
  } else {
    throw new Error(text);
  }
}

export default function App(_props) {
  let [promise, setPromise] = useState(getRandomNumber());
  return (
    <>
      <button onClick={() => setPromise(getRandomNumber())}>
        generate random number
      </button>

      <Async promise={promise}>
        <Async.Pending><p>...waiting</p></Async.Pending>
        <Async.Fulfilled>{number => <p>The number is {number}</p>}</Async.Fulfilled>
        <Async.Rejected>{error => <p style={{ color: 'red' }}>{error.message}</p>}</Async.Rejected>
      </Async>
    </>
  )
}

This can be reproduced with a fresh React app from create-react-app and react-async installed. The fetch call has a substantial chance of failing.

Steps:

  • launch the app but don't press the button
  • refresh the page until you see the initial request come back with an error
  • press the button until a new request comes back with an error
  • observe the unhandled promise rejection

Am I doing something wrong?

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