カスタムフックをイベントで起動

Reactアプリで、ボタンなど任意のイベントに応じて API 通信(GET / POST)を実行したい場合のカスタムフックの利用例。


📦 POST通信:カスタムフックの実装

// hooks/useCreateUser.ts
import { useState, useCallback } from 'react';
import axios from 'axios';

type CreateUserParams = {
  name: string;
  email: string;
};

export const useCreateUser = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  const createUser = useCallback(async (params: CreateUserParams) => {
    setLoading(true);
    setError(null);
    setSuccess(false);
    try {
      await axios.post('/api/users', params);
      setSuccess(true);
    } catch (e: any) {
      setError(e.response?.data?.message || '登録に失敗しました');
    } finally {
      setLoading(false);
    }
  }, []);

  return { createUser, loading, error, success };
};

🧪 実際の使用例

// components/UserForm.tsx
import { useState } from 'react';
import { useCreateUser } from '../hooks/useCreateUser';

export const UserForm = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const { createUser, loading, error, success } = useCreateUser();

  const handleClick = () => {
    createUser({ name, email });
  };

  return (

<div>
      <input value={name} onChange={(e) => setName(e.target.value)} placeholder="名前" />
      <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="メール" />
      <button onClick={handleClick} disabled={loading}>
        登録
      </button>
      {loading && 
<p>送信中...</p>}
      {error && <p style={{ color: 'red' }}>{error}</p>}
      {success && 
<p>登録が完了しました!</p>}
    </div>
  );
};

コメントを残す 0

Your email address will not be published. Required fields are marked *