Breaking News: Grepper is joining
You.com.
Read the official announcement!
Check it out
SEARCH
COMMUNITY
API
DOCS
INSTALL GREPPER
Log In
Signup
Alvin Acosta
May 19, 2022
Follow Alvin Acosta
Twitter
Facebook
Reddit
Hacker News
LinkedIn
useAxios custom hook
create useAxios custom hook for fetching data
import { useEffect, useState } from "react"; import axios from "axios"; axios.defaults.baseURL = "https://jsonplaceholder.typicode.com"; export const useAxios = (axiosParams) => { const [response, setResponse] = useState(null); const [error, setError] = useState(""); const [loading, setloading] = useState(true); const fetchData = async (params) => { try { const response = await axios.request(params); setResponse(response.data); } catch (err) { setError(err.message); } finally { setloading(false); } }; useEffect(() => { fetchData(axiosParams); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return { response, error, loading }; };
use custom hook in your component/s
import {useAxios} from "./useAxios"; const Container = () => { const { response, error, loading } = useAxios({ url: "/users", method: "get", }); return ( <div className="App"> <h1>Users</h1> {loading ? ( <p>loading...</p> ) : ( <div> {error ? ( <div> <p>{error.message}</p> </div> ) : ( <div> {response.length > 0 && ( <ul> {response.map((item, i) => ( <li key={i}>{item.name}</li> ))} </ul> )} </div> )} </div> )} </div> )}; export default Container;