React おもろい

React を今月から始めてみたけど、おもろい! サスペンスを使ったデータ取得までしか見てないけど、とりあえず体感したかったし、公式を参考に適当に実装(^^♪。

//エラー境界
class ErrorBoundary extends React.Component {...}

//リソース
const userResource = (userId) => {
  let status = 'pending';
  let result;

   const suspender = fetch(
  `https://jsonplaceholder.typicode.com/users/${userId}`
    )
   .then((res) => res.json())
   .then(
      (user) => {
        status = 'fulfuild';
        result = user;
      },
      (error) => {
        status = 'rejected';
        result = error;
      }
    );
   const load = () => {
    if (status === 'pending') {
      throw suspender;
    } else if (status === 'fulfuild') {
      return result;
    } else {
      throw result;
    }
  };

  return { load, userId };
};

//次のユーザID
const getNextUserId = (userId) => {
  const nextId = userId === 10 ? 1 : userId + 1;
  return nextId;
};

//ユーザ
const User = ({ resource }) => {
  const user = resource.load();
  return <>{user.name}</>;
};

//レンダー
const Sample = () => {
  const [resource, setResource] = useState(userResource(1));

  const handleClick = () => {
    setResource(userResource(getNextUserId(resource.userId)));
  };
  return (
    <>
      <ErrorBoundary>
        <Suspense fallback={<>loading...</>}>
          <User resource={resource} />
        </Suspense>
      </ErrorBoundary>
      <div>
         //クリックすると別のユーザ名が表示される
        <button onClick={handleClick}>NEXT</button>
      </div>
      <GlobalStyle />
    </>
  );
};