try-catch statement in React JSX - reactjs

According to the JSX reference, this is what a try-catch statement must look like
try {
statement*
} [catch (varname : type) {
statement*
}]* [finally {
statement*
}]
I tried the following
try {
console.log(window.device.version)
} catch (e : TypeError) {
console.log('Error')
}
Which results in the error
Module build failed: SyntaxError: Unexpected token, expected ) (11:15)
9 | try {
10 | console.log(window.device.version)
11 | } catch (e : TypeError) {
| ^
12 | console.log('Error')
13 | }
14 | return (
What is the correct way to use a try-catch statement in JSX then ?

React JSX
It looks like a TypeScript style. Just use try{ } catch(e) { console.error(e); } would be fine.
Take a look at MDN, and don't forget that JSX is just a syntax sugar for React.createElement.
JSX - a faster, safer, easier JavaScript
The link you mentioned is not react React JSX, but a whole new thing call DeNA JSX.
Take a look at this issue in DeNA JSX, and this PR.

In JSX or JavaScript you can write it like this
try {
console.log(window.device.version)
} catch (e) {
console.log('Error')
}
If you are using TypeScript your previous code should work
Hope that helps

The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The final statement lets you execute code, after try and catch, regardless of the result.
The basic concept goes like this:
try {
// Block of code to try
}
catch(err) {
// Block of code to handle errors
}
So, let's now make a scenario where an error would occur:
// It will try to run the task, but it will fail
try {
eval(console.log("Hello world)); // Just add the missing quote at the end of 'world' word and it will pass :)
}
// So, here is where we catch the error and display it to the user
catch(error) {
console.error(error);
// expected output:
// "message": "Uncaught SyntaxError: Invalid or unexpected token"
// Note - error messages will vary depending on browser
}

Exception handling has the following syntax..
try {
// code...
} catch (err) {
// error handling
}
See this: https://javascript.info/try-catch
But try-catch will not catch all the errors in React.js code. Try-catch will detect errors in an imperative code whereas React is declarative in nature
Use error boundaries as defined in React 16 and above..
Create a component using componentDidCatch
Surround your component to be tested using the error boundary.
See this-(official react docs):https://reactjs.org/blog/2017/07/26/error-handling-in-react-16.html

try{
// code for error testing
}
catch (e) {
// code for error handeling
console.log(e)
}

Related

React Hook Effects Error not able to deploy the website

useEffect(() => {
let val = window.ethereum.isConnected();
if(val)
{
console.log("here");
getAddress();
toggleConnect(val);
updateButton();
}
window.ethereum.on('accountsChanged', function(accounts){
window.location.replace(location.pathname)
})
});
React Hook useEffect contains a call to 'toggleConnect'. Without a list of dependencies, this can lead to an infinite chain of updates. To fix this, pass [location.pathname] as a second argument to the useEffect Hook.
Please, could anyone help with fixing this error?
I tried fixing it by using // eslint-disable-next-line. The warning went away but I am facing issues deploying the website online. It is giving error messages.

How to avoid Error: NotAllowedError: Document is not focused?

I am working on a react component which has a copy button handler like this:
function copyConnHandler() {
let text = copyConnRef.current.getAttribute("connid");
if (navigator && copyConnRef) {
navigator.clipboard.writeText(text);
copyConnRef.current.setAttribute("data-hint", "copied");
}
setTimeout(() => {
if(copyConnRef){
copyConnRef.current.setAttribute("data-hint", "copy");
}
}, 700);
}
This works in most scenarios but throws Error: NotAllowedError: Document is not focused in some cases. How can I prevent it from happening? (Found the error in production using Sentry).
PS: The error was occurring in electron and chrome browsers

Jest, Enzyme, React, Next.js, Typescript .default is not a constructor

I want to write simple test checking if my next.js page loads without errors.
I followed this tutorial and I almost got it working, but simple-react-validator stays in my way with the following error when i run npm run test which justs run jest behind the scene:
TypeError: simple_react_validator_1.default is not a constructor
private validator : SimpleReactValidator = new SimpleReactValidator({
| ^
96 | locale: 'en',
97 | autoForceUpdate: this,
98 | validators: {
Before I couldn't even use simple-react-validator with my Typescript Next.js application. I needed to add to next-env.d.ts this:
declare module 'simple-react-validator' {
const content: any;
export default content;
}
Then I was able to use it in my application, but tests are complaining about constructor.
What can cause this issue? Maybe I need to somehow explicitly tell it somewhere what SimpleReactValidator is but I don't know where.
After some time I figured it out.
If using typescript, you must to wrap your mock in 'default' property:
jest.mock('simple-react-validator', () => {
return {
'default': class SimpleReactValidatorMock {
allValid() { return true; }
fieldValid() { return true; }
message() { return ''; }
}
}
});
I found the answer here:
https://github.com/kulshekhar/ts-jest/issues/120#issuecomment-283653644

React testing through jest gives an unexpected error

I'm using JEST to test my react app.
I get the error and some text as in the image below.
Also, the code for my test case(named: TodoApp.test.jsx) is as :
it("should add todo ...", () => {
// const text = "Suzal is trying react";
// I commented out the other lines because the test
// only gave error when this line was included.
const todoApp = TestUtils.renderIntoDocument(<TodoApp />);
// todoApp.state = {
// todos: []
// }
// todoApp.handleAddTodo(text);
// expect(todoApp.state.todos[0].text).toBe(text);
});
If extra code/description is needed then please do ask. The complete file is on Github : TodoApp.test.jsx
Links that I already have gone through
https://github.com/facebook/react/issues/11098
https://github.com/facebook/jest/issues/4597
I cloned your repo and started commenting things out and found that there seems to be something going on with TodoApi.getTodos() on line 15 of TodoApp.jsx in the constructor when setting your initial state. If you remove the call to TodoApi.getTodos and replace with with an empty array the test errors disappear. You may need to create a mock function for TodoApi.getTodos to get your tests to pass.
https://facebook.github.io/jest/docs/en/mock-functions.html

Karma and React, have warnings to cause errors

I am using Karma with mocha to test my React components. I have some warnings displayed when the PropTypes are not matched. However it would be really interesting to have these warnings to cause an actual error, as to track down the test and fix it.
Do you know how this could be achieved?
You can replace the console.warn method with your own and throw when the message provided matches a certain pattern.
let warn = console.warn;
console.warn = function(warning) {
if (/(Invalid prop|Failed propType)/.test(warning)) {
throw new Error(warning);
}
warn.apply(console, arguments);
};
Small improvements to accepted answer: console.error instead of console.warn as spain-train mentioned, added 'Failed prop type' to regex, as only then it works with React 15.3.1, and made the code more strict eslint friendly.
const error = console.error;
console.error = function(warning, ...args) {
if (/(Invalid prop|Failed prop type)/.test(warning)) {
throw new Error(warning);
}
error.apply(console, [warning, ...args]);
};
2021 update:
const consoleError = console.error;
console.error = function (...args) {
if (/(Invalid prop|Failed propType|Failed .+ type)/.test(args[0])) {
const errorMessage = args.reduce((p, c) => p.replace(/%s/, c));
throw new Error(errorMessage);
}
consoleError.apply(console, args);
};
Failed prop type is now Failed %s type: %s%s. It uses string substitutions to write to console. Here is the code in React.

Resources