Skip to content

useAxios is a react hook that is type safe with error handling.

License

Notifications You must be signed in to change notification settings

sjblurton/use-axios

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

useAxios

useAxios, for CREATE, UPDATE, DELETE, and useAxiosGet to read data form a rest API, stores it in the cache.

All error handling, and a status for pending, error idle, and success with the REST API.

install

npm i @sjblurton/use-axios

yarn add @sjblurton/use-axios

Import useAxios

import { useAxiosGet, useAxios }from "@sjblurton/use-axios-get";

To call the hooks...

const [status, response, error, setAPICall] = useAxios<RequestData, ServerResponseData>();
const [status, data, error, mutate] = useAxiosGet<Data>('url')

status

returns a string of 'idle', 'pending', 'error', or 'success'

response

returns an AxiosResponse or undefined if not responded.

error

returns an AxiosError response or undefined if no error

data

returns the response data or undefined

setAxiosReq

takes one AxiosRequestConfig object with two values required, the url string and method as a string. plus all the optional ones, refer to the Axios docs here: https://axios-http.com/docs/req_config

setAxiosReq({
              method: 'DELETE',
              url: '/user/2',
          })

useAxiosGet

function App() {
  const todos = useAxiosGet<MockData>(
    "https://jsonplaceholder.typicode.com/todos"
  );

  if (todos.status === "pending") return <div>loading...</div>;
  if (todos.status === "error") return <div>{todos?.error?.message}</div>;

  return (
    <div className="App">
      {todos?.data?.map((todo) => (
        <h2>{todo.title}</h2>
      ))}
      <button onClick={todos?.mutate}>Mutate</button>
    </div>
  );
}

Links

GitHub: https://github.com/sjblurton/use-axios-get
NPM: https://www.npmjs.com/package/@sjblurton/use-axios-get

About

useAxios is a react hook that is type safe with error handling.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published