0

I want to be able to make my own state change when when the return from useTransition completes. That is, currently, in the example below, isPending toggles from true to false, but that's not enough. I want to be able to execute code on that change.

That is, in the example below, I would like to possible do something similar to what useEffect does, and have the code that is returned from the startTransition execute when the pending event changes, but that does not work.

Any other options?

onClick={() => {
          startTransition(() => {
            const nextUserId = getNextId(resource.userId);
            setResource(fetchProfileData(nextUserId));
            return () => { DO THIS CODE WHEN PENDING BECOMES FALSE }
          });
        }}
function App() {
  const [resource, setResource] = useState(initialResource);
  const [startTransition, isPending] = useTransition({
    timeoutMs: 3000
  });
  return (
    <>
      <button
        disabled={isPending}
        onClick={() => {
          startTransition(() => {
            const nextUserId = getNextId(resource.userId);
            setResource(fetchProfileData(nextUserId));
          });
        }}
      >
        Next
      </button>
      {isPending ? " Loading..." : null}
      <ProfilePage resource={resource} />
    </>
  );
}
taylor.2317
  • 582
  • 1
  • 9
  • 23
Peter Kellner
  • 14,748
  • 25
  • 102
  • 188

1 Answers1

1

It's is not possible within the startTransition call / useTransition config. You can use useEffect/useLayoutEffect to run some code after resource update.

useEffect/useLayoutEffect(() => {
    // some code after resource state update
}, [resource])
jkaczmarkiewicz
  • 1,500
  • 6
  • 17