Cómo crear un custom hooks con axios

Cómo crear un custom hooks con axios

Crear aplicación

npm init vite@latest

Instalar Axios

npm i axios

Crear hook (useAxios.js)

import { useEffect, useState } from "react";
import axios from "axios";

const useAxios = (method, url, body) => {
  const [data, setData] = useState([]);
  const [error, setError] = useState(null)

  useEffect(() => {
    const headers = {
      'Content-Type': 'application/json'
    };

    axios
      .request({
        method: method,
        url: url,
        data: body,
        headers: headers
      })
      .then(res => {
        setData(res.data);
      })
      .catch(error => {
        setError(error.message);
      });
  }, []);

  return { data, error };
};

export default useAxios;

Utilización del hook (app.js)

import useAxios from './hooks/useAxios'

function App() {
  const { data, error } = useAxios(
    'get',
    'https://jsonplaceholder.typicode.com/users',
    {
      username: 'test',
    },
  )

  return (
    <div className="App">
      {error ? <div>{error}</div> : JSON.stringify(data)}
    </div>
  )
}

export default App