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