axios_React

26748 ワード

axios


GET:クエリーデータaxios.post()POST:データ登録
//파라미터에는 API의 주소를 넣는다
//두번째 파라미터에 등록하고자 하는 정보를 넣을 수 있다
axios.post('/users', {
  username: 'blabla',
  name: 'blabla'
});
PUT:データの修正
DELETE:データの削除

設定

$ yarn add axios $ npm install axios

使用


要求に対してステータス管理を行う場合、以下の3つのステータス管理を実行します.
1.要求の結果
2.ロードステータス
3.エラー
import React, { useState, useEffect } from 'react';
import axios from 'axios';

function Users() {
  const [users, setUsers] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        // 요청이 시작 할 때에는 error 와 users 를 초기화하고
        setError(null);
        setUsers(null);
        // loading 상태가 활성화 됐을때 true로 로딩중..
        setLoading(true);
        const response = await axios.get(
          'https://jsonplaceholder.typicode.com/users'
        );
        setUsers(response.data); // 데이터는 response.data 안에 들어있습니다.
      } catch (e) {
        //response의 주소가 맞지 않을때 에러가 발생한다
        setError(e);
      }
      setLoading(false);
    };

    fetchUsers();
  }, []);

  if (loading) return <div>로딩중..</div>;
  if (error) return <div>에러가 발생했습니다</div>;
  if (!users) return null;
  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>
          {user.username} ({user.name})
        </li>
      ))}
    </ul>
  );
}

export default Users;

リファレンス

  • userEffectで最初のパラメータとして登録されている関数はasyncを使用できないため、asyncを使用する新しい関数を関数内部で宣言する必要があります.
  • userReducerの使用

    const reducer = (state, action) => {
      switch (action.type) {
        case 'LOADING':
          return {
            loading: true,
            data: null,
            error: null,
          };
        case 'SUCCESS':
          return {
            loading: false,
            data: action.data,
            error: null,
          };
        case 'ERROR':
          return {
            loading: false,
            data: null,
            error: action.error,
          };
        default:
          throw new Error(`Unhandled action type: ${action.type}`);
      }
    };
    
    const UserList = ({ users }) => {
      const [state, dispatch] = useReducer(reducer, {
        loading: false,
        data: null,
        error: null,
      });
    
      const fetchUsers = async () => {
        dispatch({ type: 'LOADING' });
        try {
          const response = await axios.get(
            'https://jsonplaceholder.typicode.com/users'
          );
          dispatch({ type: 'SUCCESS', data: response.data });
        } catch (e) {
          dispatch({ type: 'ERROR', error: e });
        }
      };
    
      useEffect(() => {
        fetchUsers();
      }, []);
    
      //state.data를 user 키워드로 조회
      const { loading, data: user, error } = state;
    
      if (loading) return <div>로딩중..</div>;
      if (error) return <div>에러가 발생했습니다</div>;
      if (!user) return null;

    後でデータをロード

    async function getUsers() {
      const response = await axios.get(
        'https://jsonplaceholder.typicode.com/users'
      );
      return response.data;
    }
    
    const useAsync = (getUsers, deps = [], skip = true) => {
      const [state, dispatch] = useReducer(reducer, {
        loading: false,
        data: null,
        error: null,
      });
    
      const fetchData = async () => {
        dispatch({ type: 'LOADING' });
        try {
          const data = await callback();
          dispatch({ type: 'SUCCESS', data });
        } catch (e) {
          dispatch({ type: 'ERROR', error: e });
        }
      };
    
      if (loading) return <div>로딩중..</div>;
      if (error) return <div>에러가 발생했습니다</div>;
      if (!user) return <button onClick={refetch}>불러오기</button>;
      
      useEffect(() => {
        if (skip) return;
        fetchData();
      }, []);
    
      return [state, fetchData];