S
S
Snelsi2019-06-30 16:50:32
React
Snelsi, 2019-06-30 16:50:32

How to handle functional component error in React 16.8?

The component takes a string in props and tries to convert it into a regular expression.

function ControlString(props) {
    const regExp = new RegExp(props.template, "g");
    ...
}

The update is called for every character entered, so if you try to type '\d' in the parent, the constructor will throw an error on a single slash.
5d18bdaa3dba2054363974.png
componentDidCatch does not work in functions. How can this exception be handled without casting the entire component to a class?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Snelsi, 2019-07-01
@Snelsi

The error is still easier to handle not in the child, but in the parent.
The solution came down to this:

const [input, setInput] = useState("");
const [expression, setExpression] = useState("");

const updateInput = e => {
  setInput(e.target.value);
  try {
    new RegExp(e.target.value, "g");
    setExpression(e.target.value);
  } catch (e) {
    setExpression(".^");
  }
};

return (
  <input onChange={updateInput} />
  <ControlString template={expression} />
);

V
Vladimir Proskurin, 2019-06-30
@Vlad_IT

Generally, there are fuses . But you can handle the error when calling the RegExp constructor via try-catch,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question