errorboundary

This commit is contained in:
Tyrel Souza 2022-09-26 16:07:26 -04:00
parent c664806c7b
commit c7b46dadc3
No known key found for this signature in database
GPG Key ID: F3614B02ACBE438E
3 changed files with 40 additions and 4 deletions

View File

@ -0,0 +1,24 @@
import { Component } from "react";
class ErrorBoundary extends Component {
constructor() {
super();
this.state = {
hasError: false,
};
}
componentDidCatch(error) {
console.log(error)
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
return <p>Something went wrong</p>;
}
return this.props.children;
}
}
export default ErrorBoundary;

View File

@ -1,5 +1,6 @@
import { Component, Fragment } from "react";
import UsersContext from "../store/users-context";
import ErrorBoundary from "./ErrorBoundary";
import classes from "./UserFinder.module.css";
import Users from "./Users";
@ -35,10 +36,15 @@ class UserFinder extends Component {
render() {
return (
<Fragment>
<div className={classes.finder}>
<input type="search" onChange={this.searchChangeHandler.bind(this)} />
</div>
<Users users={this.state.filteredUsers} />
<ErrorBoundary>
<div className={classes.finder}>
<input
type="search"
onChange={this.searchChangeHandler.bind(this)}
/>
</div>
<Users users={this.state.filteredUsers} />
</ErrorBoundary>
</Fragment>
);
}

View File

@ -13,6 +13,12 @@ class Users extends React.Component {
};
}
componentDidUpdate(){
if (this.props.users.length === 0) {
throw new Error('no users')
}
}
toggleUsersHandler() {
this.setState((curState) => {
return {