I searched for error handling in react.
and i found componentDidCatch.
but componentDidCatch only catch in render.
I want to catch a error in method.
My source
import React from 'react';
class Child extends React.Component{
handleError = () => {
throw new Error('Error');
}
render() {
return (
<button onClick={this.handleError}>Error</button>
);
}
}
export default Main extends React.Component {
componentDidCatch(error,info) {
console.log(error, info); // NOT WORK
}
render() {
return (<Child/>);
}
}
You can check official React's Error handeling page where they use this code:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Display fallback UI
this.setState({ hasError: true });
// You can also log the error to an error reporting service
logErrorToMyService(error, info);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
this codebox that is official Dan Abramov's (creator of React) CodeBox: https://codepen.io/gaearon/pen/wqvxGa?editors=0010
Related
I am working with a functional component in which I implemented Lazy loading and compoent is lazy loading fine. But in a sanario while there is no component ErrorBoundary is not working and app is breaking with no fallback UI/msg.
My code is
export const SiteContent = () => {
const [selectedOption, setSelectedOption] = useState(null);
let LazyLoadedComponent = null;
if (selectedOption?.component) {
LazyLoadedComponent = React.lazy(
() =>
import(
`./components/${selectedOption.option.value}/${selectedOption.option.value}`
)
);
}
return (
<>
<ErrorBoundary>
<Suspense fallback={<div>Loading....</div>}>
{selectedOption?.component && LazyLoadedComponent && (
<LazyLoadedComponent />
)}
</Suspense>
</ErrorBoundary>
</>
);
};
ErrorBoundary code is
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
export default ErrorBoundary;
Try setting your hasError state to true in the componentDidCatch method.
componentDidCatch(error, errorInfo) {
this.setState({ hasError: true});
}
You have to set the hasError state to true for the fallback UI to be shown.
Change your ErrorBoundary's componentDidCatch to :
componentDidCatch(error, errorInfo) {
this.setState({ hasError: true});
}
im upgrading an old react pp to use functional components. I am having troubles with the error boundary class component . I simply dont understand how to update the static getDerivedStateFromError what is the correct syntax to update this function?
initial component
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
};
}
static getDerivedStateFromError(_error) {
return { hasError: true };
}
componentDidCatch(error, info) {
sendError("ErrorBoundary", { info }, error);
}
render() {
if (this.state.hasError) {
return <ErrorText />;
} else {
return this.props.children;
}
}
}
New component, which is imssing something for sure as it never sets the error to true, which was done by the static function..
const ErrorBoundary = (props) => {
const [hasError, setHasError] = useState(false)
try {
if (hasError) {
return <ErrorText />;
} else {
return props.children;
}
} catch {
sendError("ErrorBoundary", { info }, error);
}
}
There's no way to do the componentDidCatch nor the getDerivedStateFromError on hooks right now. Here's the documentation:
https://reactjs.org/docs/hooks-faq.html#from-classes-to-hooks
getSnapshotBeforeUpdate, componentDidCatch and getDerivedStateFromError: There are no Hook equivalents for these methods yet, but they will be added soon.
I have a component wrapped in an Error Boundary, when a button is clicked a validate() function is called, this function throws an error if there is not information provided however the ErrorBoundary is not catching this error.
Render function on Component
return (
<ErrorBoundary>
...
<Playlist
...
onClick={this.addPlaylistToSpotify} // this function can throw an error
...
/>
</ErrorBoundary>
);
Function with error
addPlaylistToSpotify = () => {
try {
addPlaylist(this.state.newPlaylist); // this function throws an error on validate()
} catch (error) {
throw new Error(error);
}
...
};
ErrorBoundary Component
import React, { Component } from "react";
import { ErrorOverlay } from "../../components/index";
import styles from "./ErrorBoundary.css";
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: ""
};
}
componentDidCatch(error, errorInfo) {
this.setState({
hasError: true,
error: error,
errorInfo: errorInfo
});
// TODO: log the error somewhere in the db
}
dismiss() {
this.setState({
hasError: false,
error: null,
errorInfo: ""
});
}
render() {
if (this.state.hasError) {
return (
<ErrorOverlay message={this.state.errorInfo} dismiss={this.dismiss} />
);
} else {
return this.props.children;
}
}
}
Any help would be hugely appreciated, thanks!
Any help would be hugely appreciated. Thanks!
From React docs
https://reactjs.org/docs/error-boundaries.html#how-about-event-handlers
Note
Error boundaries do not catch errors for:
Event handlers
Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
Server-side rendering
Errors thrown in the error boundary itself (rather than its children)
In your code, the error is thrown from an event handler (addPlaylistToSpotify) so componentDidCatch can't catch the error. Therefore you need to do something like this:
import React from 'react';
export class Playlist extends React.Component {
constructor (props) {
super(props);
this.state = {
error: false
// ...
}
}
addPlaylistToSpotify = () => {
try {
// Something throws an error here.
} catch (error) {
this.setState({ error: true });
}
}
render() {
if (this.state.error) {
throw new Error('I crashed!');
}
return (
<div>
...
<button onClick={this.addPlaylistToSpotify}>Add song</button>
...
</div>
)
}
}
I hope this helps.
I am using react and I have componentWillMount which looks like this
componentWillMount() {
axios.get('/user').then(response => {
console.log(response.data.user)
if (response.data.user) {
} else {
this.props.history.replace('/signup');
}
});
}
Notice this line here in the code.
if (response.data.user) {
}
Now, How can I make my container render if the condition is met?
You just need to set the user variable in the component state once you received it in then method, and later you can use it in your render method:
import React from 'react'
class App extends React.Component {
constructor (props) {
super(props)
this.state = { user: null }
}
componentWillMount() {
axios.get('/user').then(response => {
if (response.data.user) {
this.setState({ user: reaponse.data.user )}
} else {
this.props.history.replace('/signup')
}
})
}
render() {
// Do something with the user
if (this.state.user) {
return <div>{this.state.user.name}</div>
}
return <div />
}
}
Hy, render conditionally based on state.
import React from "react";
class ExampleComponent extends React.PureComponent {
state={ user: null }
static getDerivedStateFromProps(nextProps, prevState){
if(!prevState.user && state.user){
this.props.history.replace('/signup');
}
else return null;
}
componentWillMount() {
axios.get('/user').then(response => {
console.log(response.data.user)
if (response.data.user) {
this.setState({ user: response.data.user )}
}
});
}
render() {
const { user } = this.state;
return user ? <div>have user, can return null</div> : <div>loading user</div>
}
}
export default ExampleComponent;
I reactjs I have a component and it has this code to detect whether there is a click outside the component:
export class Cart extends React.Component {
handleClick(e) {
if (!ReactDOM.findDOMNode(this).contains(e.target)) {
console.log('testing=e.target', e.target)
}
}
componentWillMount() {
document.addEventListener('click', this.handleClick, false);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick, false);
}
render()
{
return (<div>hello</div>)
}}
However I am getting an error in the findDOMNode statement:
Uncaught Error: Element appears to be neither ReactComponent nor DOMNode
How can I fix this?
You can add id property to the div component, and then refactor the code as follows:
export class Cart extends React.Component {
handleClick(e) {
if (e.target.id === 'div') {
console.log('inside')
} else {
console.log('outside!')
}
}
componentWillMount() {
document.addEventListener('click', this.handleClick, false);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClick, false);
}
render()
{
return (
<div id="div">
hello
</div>)
}
}