Axios 인터셉터 후크 Typescript

재게시됨

안녕,
그 전에 다음과 같은 첫 번째 NPM 패키지를 게시했습니다.

문제
  • JavaScript에서 빌드, 제안이 없기 때문에 사용자가 소품에 대해 알기 어렵습니다.
  • multipart/form-data 콘텐츠 유형을 호출할 방법이 없습니다.

  • 새로운 기능
  • TypeScript로 개발되었습니다.
  • Application/json 및 multipart/form-data에 대한 별도의 후크.
  • 구성에 유형을 사용할 수 있습니다. (APIConfig).

  • 인터셉터

    Axios 인터셉터는 axios를 사용하여 각 호출 요청 및 응답 변환에 사용되는 메서드입니다. 인터셉터는 API 요청을 호출하기 전과 API에서 응답을 받을 때 요청을 변환하는 데 도움이 됩니다. 마치 미들웨어처럼 작동합니다.

    구성

    npm 패키지를 설치해야 합니다axios-hook-typescript.

    Github 레포: ( https://github.com/sheikhfahad67/axios-hook-typescript )

    터미널에서 명령을 실행합니다.npm install axios react-toastify axios-hook-typescript

    액시오스-후크-타입스크립트





    react-tostify 통합이 내장된 axios에 대한 반응 후크. 최소한의 구성으로 사용이 간편합니다.



    특징


  • 당신이 잘 알고 있는 모든 axios 굉장함
  • 제로 구성이지만 필요한 경우 구성 가능
  • 더 나은 토스트 메시지를 위한 통합 react-toastify
  • 파일 관리 최소화

  • 설치


    npm install axios react-toastify axios-hook-typescript

    axios and react-toastify are peer dependencies and needs to be installed explicitly



    예시




    import { useEffect, useRef } from 'react';
    import {
      ApiConfig,
      useJsonApiInterceptor,
      useMultipartInterceptor,
    } from 'axios-hook-typescript';
    import { ToastContainer } from 'react-toastify';
    import 'react-toastify/dist/ReactToastify.css';
    import './App.css';
    
    interface todosObject {
      userId: number;
      id: number;
      title: string;
      completed: boolean;
    }
    
    const App = () => {
      const { apiHandler: jsonApiHandler, data: jsonData } =
        useJsonApiInterceptor();
      const { apiHandler: multipartApiHandler } = useMultipartInterceptor();
      const inputRef = useRef(null);
    
      const getTodos = async () => {
        const config: ApiConfig = {
          url: 'https://jsonplaceholder.typicode.com/todos',
          method: 'GET',
          displayToast: true,
          successMessage: 'Fetch all todos',
          theme: 'colored',
        };
        await jsonApiHandler(config);
      };
    
      useEffect(() => {
        getTodos();
      }, []);
    
      const handleFileChange = async (e: any) => {
        const { files: newFiles } = e.target;
        const formData = new FormData();
        formData.append('image', newFiles[0]);
    
        const config: ApiConfig = {
          url: 'http://localhost:8000/files',
          data: formData,
          method: 'POST',
          displayToast: true,
          successMessage: 'File uploaded successfully',
        };
        await multipartApiHandler(config);
      };
    
      return (
        <div className='App'>
          <ToastContainer />
          <h1>Axios Interceptor Examples</h1>
          <input
            id='file'
            type='file'
            multiple
            ref={inputRef}
            onChange={handleFileChange}
          />
          <button className='submit-btn' type='submit'>
            Upload
          </button>
          <div style={{ marginTop: '50px', border: '1px solid green' }}>
            {jsonData &&
              Object.keys(jsonData).length > 0 &&
              jsonData.map((todo: todosObject) => (
                <h1 key={todo.id}>{todo?.title}</h1>
              ))}
          </div>
        </div>
      );
    };
    
    export default App;
    


    선적 서류 비치



    후크



    useJsonApiInterceptor - for content-type: application/json.
    useMultipartInterceptor - for content-type: multipart/form-data



    반품



    다음 필드를 반환합니다.


    필드
    유형
    설명


    데이터
    물체
    api의 응답을 반환합니다(res.data).

    대기 중
    부울
    로드 목적을 위해 가져오는 동안 반환true하고 완료 또는 실패 후 false를 반환합니다.

    api핸들러
    기능
    전달만 하면 필요할 때 호출을 제어할 수 있는 기능config


    무기명 토큰의 경우



    인증 토큰을 다른 이름으로 저장해야 인터셉터가 자동으로 가져옵니다.

    localStorage.setItem('authToken', <YOUR TOKEN>);



    기본 URL에 대한 환경 변수


    .env 또는 .env.local 파일에 env 변수를 추가하십시오.

    REACT_APP_BASE_URL="https://jsonplaceholder.typicode.com"



    구성 소품



    유형



    ApiConfig - for api configurations




    필드
    유형
    설명


    방법
    끈
    '받기', '게시', '넣기', '삭제', '패치'

    URL
    끈
    그것은 당신의 종점이 될 것입니다

    지연
    숫자
    기본 5000

    데이터
    물체
    게시, 넣기, 패치 요청에 필요

    성공 메시지
    끈
    '모든 메시지'

    위치
    끈
    '오른쪽 위', '왼쪽 위', '가운데 위', '왼쪽 아래', '오른쪽 아래', '가운데 아래'

    진행률 표시줄 숨기기
    부울
    true 또는 false
    주제
    끈
    '밝음', '어두움', '색상'


    특허



    MIT

    좋은 웹페이지 즐겨찾기