Skip to content

Errors in the useReduce reducer function are thrown differently than React #2750

Closed
@mischnic

Description

@mischnic

Reproduction

https://codesandbox.io/s/preact-usereducer-error-lr1mx?file=/src/index.js

import React, { useEffect } from "preact/compat";
import ReactDOM from "preact/compat";
/*/
import React, { useEffect } from "react";
import ReactDOM from "react-dom";
*/

function useTest() {
  try {
    let [, dispatch] = React.useReducer(() => {
      throw new Error("X");
    }, "a");

    return {
      load() {
        dispatch("b");
      }
    };
  } catch (e) {
    console.log("useReducer", e.message);
    throw e;
  }
}

function Test() {
  let { load } = useTest();
  useEffect(() => {
    try {
      load();
    } catch (e) {
      console.log("dispatch", e.message);
      throw e;
    }
  });

  return "Test";
}

class Catcher extends React.Component {
  constructor() {
    super();
    this.state = { error: null };
  }

  componentDidCatch(error) {
    this.setState({ error: error.message });
  }

  render() {
    if (this.state.error) {
      return <p>Something went badly wrong: {this.state.error}</p>;
    }
    return this.props.children;
  }
}

function App() {
  return (
    <Catcher>
      <Test />
    </Catcher>
  );
}

ReactDOM.render(<App />, document.getElementById("root"));

Steps to reproduce

Open reproduction

Expected Behavior

🤷‍♂️ (not sure how far you want to take the "1:1" compatibility to React 😄 )

Actual Behavior

An error is thrown in the reducer function.

Preact throws this error back through the the dispatch() call (so load() in this case). ("dispatch" is logged).

React throws this error back "through the the useReduce() call". ("useReducer" is logged).

Context

This messes with @testing-library/preact-hooks-testing-library because you need to catch the actual calls and can't rely on result.error. testing-library/preact-hooks-testing-library#3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions