Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

new_bird-hyun

React - toast 에러 처리 + ErrorBoundary 병행 본문

코딩 공부

React - toast 에러 처리 + ErrorBoundary 병행

새혀니 2025. 4. 14. 13:50

npm install react-toastify

import { toast, ToastContainer } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

function fetchUser() {
  fetch('/api/user')
    .then((res) => {
      if (!res.ok) throw new Error('사용자 정보를 불러오지 못했습니다.');
      return res.json();
    })
    .then((data) => console.log(data))
    .catch((err) => toast.error(err.message));
}

export default function UserPage() {
  return (
    <>
      <button onClick={fetchUser}>유저 불러오기</button>
      <ToastContainer />
    </>
  );
}


// ErrorBoundary.tsx
class ErrorBoundary extends React.Component {
  state = { hasError: false };
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) return <h2>문제가 발생했습니다.</h2>;
    return this.props.children;
  }
}