Giter VIP home page Giter VIP logo

axios-hooks's People

Contributors

8ensmith avatar charkour avatar dependabot[bot] avatar eelkevdbos avatar eperedo avatar hsz avatar jtongay avatar kasperbe avatar kylorhall avatar lpgera avatar lukaskral avatar mosattler avatar moussa-kalam avatar nanto avatar optic-release-automation[bot] avatar renovate-bot avatar simoneb avatar songkeys avatar svish avatar thupi avatar verekia avatar vladi-strilets avatar vmlopezr avatar ymor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

axios-hooks's Issues

Feature request: Enable caching for manual requests

When using manual mode (i.e. when the manual option is set to true) the execute function returned does not use the cache i.e.

return [
    state,
    configOverride => {
      return executeRequestWithoutCache(
        { ...config, ...configOverride },
        dispatch
      )
    }
  ]

It would be great if a user could choose to use the manual execute function which does have caching enabled.

The scenario I have is where a user can undo an operation, which manually triggers execute, but I'd like to use a cached result instead of going back to the server.

Thoughts?

Custom reducer and default initial values

Sometimes I need to modify the data after it's returned from the webservice before rendering. It would be nice to pass in a custom reducer to handle this, unless you know of a better way.

It would also be nice to pass in a the initial data that is returned for rendering before the call is made. Most of the time this would be an empty object or empty array. It would save me from having to check for undefines in a bunch of places while rendering.

What do you think about adding this to the options object?
{ reducer: myCustomReducer, initialData: [] }

Default value for data, possible?

Hi, thanks for your little gem. I was able to simplify my code from

export default function InvoicesDashboard() {
    const [isLoading, setIsLoading] = useState(false);
    const [invoices, setInvoices] = useState([]);

    useEffect(() => {
        setIsLoading(true);
        api.get(`/invoices`)
            .then((data) => setInvoices(data))
            .finally(() => setIsLoading(false))
    }, []);
    
    // component rendering
    return <InvoicesTable invoices={invoices}/>
}

to this

export default function InvoicesDashboard() {
    const [{data: invoices, loading}] = useApi('/invoices');
    
    return <InvoicesTable invoices={invoices || []}/>;
}

However I need to manually handle first render when data are not already loaded with invoices || [].

I was wondering if there's any way to specify a initial value for data as in useState hook. If not it would be a great addition to this project.

Thanks.

Option to disable cache

Hi, thank you for the hook! Loving it.

I am running into a blocker though, as I am trying to use useAxios but it seems like it's impossible to disable caching for normal (not refetched) calls.

My API endpoint doesn't always return the same thing, which is a very common situation.

In my particular case, when I log out, useAxios still returns all the same data as when the user was logged in as I navigate through the app instead of allowing me to show a "you are not logged in" message.

Having the useCache option on the normal hook call seems like it would be a simple fix (rather than implementing a full fetch policy).

To be honest, it seems like an absolutely necessary feature 😅.

breaks on ie 11 from lru-cache dependency

This repo seems to break on ie11 because its importing lru-cache which does not transpile down. I've added lru-cache to my babel config would prefer a different solution if you have one?

How to record in state?

Hello, I wanted to use this module, but I didn’t understand how to write the state to the react hooks, because an error of endless re-rendering appears. In the usual use of axios, this was done in useEffect(), can show a simple example of how to record the state using your module ?

Use axios.request() instead of axios()

Hello,

Thanks for this nice hook!

Would you accept a PR that would switch this line from:

const response = await axiosInstance(config)

to

const response = await axiosInstance.request(config)

?

This would enable us to mock axios much more easily with:

jest.spyOn(axios, 'request').mockResolvedValue({data: 'ok'})

I've seen in your comment that you think we should mock the hook instead of Axios but I disagree.

2 reasons:

  • I don't want to change the logic in my existing tests when switching to useAxios (with my proposal I can simply change my jest.spyOn(axios, 'get') to jest.spyOn(axios, 'request').
  • I can test the loading state: if I mock the hook with useAxios.mockReturnValue([{ data: { ... } }]) I can only test the resolved state. What I'd like to do is for example: testing that a loader is shown, then that the data is displayed.

Thanks in advance 🙏

Adding headers after axios instance is created

As the title says I was wondering if there is a way to add headers after an instance is created? So for example before the user authenticates I don't have an authorization header. But once they login I want to inject the authorization header into the current instance. Any help would be greatly appreciated!

Constant updates make useEffect and useCallback impossible to implement

For example, I have an Axios-hook like this:

const [{ error: fileError }, onRead] = useAxios(
        { url: "/api/data/read", method: "GET" },
        { manual: true },
);

The React application I am working on has multiple different child components that can send updates to the backend API. We are utilizing a timestamp and useEffect to get any changes made to the data source:

useEffect(() => {
        onRead: {user: user }
}, [timestamp, onRead]}

The issue is that this useEffect will run thousands of times per second. It doesn't matter if I wrap onRead into another function with useCallback, it still continues to render non-stop. React guidelines as best practice would say that I should include the onRead function as a dependency in this function. Is there any reason, even with manual set to "true," that onRead is constantly changing. It makes using it dynamically with useEffect almost impossible without disregarding some best practices.

Manual true doesn't fire request

So I have the hook below with manual set to true. When running executeGet loading is set to true but the request doesn't happen.

const [{ data, loading, error }, executeGet] = useAxios({
        url: `${RENDER_ENV.API}/v1/vma`,
        params: {
            episode: episodeRef.current
        }
    }, {
        manual: true
    });

executeGet()

If change to move the config to the execute it does fire. Is this expected or a bug?

const [{ data, loading, error }, executeGet] = useAxios({}, { manual: true });

executeGet({
                url: `${RENDER_ENV.API}/v1/vma`,
                params: {
                    episode: episodeRef.current
                }
            });

Cleanup after response

When I manually execute request and useAxios return me const object it is filled with response data until next response (next response change response data). For example I want to check response status code, but what if my functional component is next rendered by an another cause and I dont't want to checking reponse again. I want only one response checking durin first render after reponse but not in next renders wchich are not related to axios (I have useEffect also and redux store reading in it). So is some cleanup procedure for cleaning axios response for example in if clause after reading response.

Conditionally call this hook

As it is not recommended to call hooks in a condition, is there any way to use this hook in certain condition?

if(ready) {
   const {data} = useAxiosHooks()
}

How to mock axiosHook for testing?

This is not a bug, but I am not sure where else to ask the question -

How can I mock the call to axios-hook for testing purposes using Jest?

Thanks!

Can't figure out how to attach completion event to PUT code

With your example here: https://www.npmjs.com/package/axios-hooks#manual-requests

function updateData() {
    executePut({
      data: {
        ...getData,
        updatedAt: new Date().toISOString()
      }
    })
  }

I want to to do work (update my own state) when the executePut completes. That is, something like passing a callback to updateData(myCallback) or updateData().then(() => console.log('done'))

Sorry for posting as an issue, but i've looked at the source and docs and it's not obvious how to do this. When calling put with axios directly, I do something like:

    axios.put(`http://localhost:4000/speakers/${speakerRec.id}`, toggledRec)
      .then(function(response) {
        updateDataRecord(toggledRec);
      })
      .catch(function(error) {
        console.log(error);
      });

Is there anyway for me to do this with axios-hooks?

Option to disable cache with makeUseAxios

Following my request in #37 (comment) and #34 it would be nice to have this

For anyone interested here's a workaround for current version

# Use a cache with expire time of 50ms
export const useApi = makeUseAxios({axios: api, cache: new LRU({ max: 10, maxAge: 50 })});

Thanks

How to mock axios response if we use axios-hooks?

Hello, I try to mock axios response by:
@react-mock/xhr: https://github.com/ctimmerm/axios-mock-adapter
axios-mock-adapter: https://github.com/ctimmerm/axios-mock-adapter
and enve jest mock: https://jestjs.io/docs/en/mock-functions#mocking-modules
They all mock axios response failed.

Do you have any example to mock axios if we use axios-hooks?

My example code:

// AxiosHooks.jsx
import React from 'react';
import useAxios from 'axios-hooks';

export default () => {
  const [{ data: getData, loading: getLoading, error: getError }] = useAxios(
    'bins/820fc',
  );

  const [
    { data: putData, loading: putLoading, error: putError },
    executePut,
  ] = useAxios(
    { url: 'bins/820fc', method: 'PUT' },
    { manual: true },
  );

  function updateData() {
    executePut({
      data: {
        ...getData,
        updatedAt: new Date().toISOString(),
      },
    });
  }

  if (getLoading || putLoading) return <p>Loading...</p>;
  if (getError || putError) return <p>Error!</p>;

  return (
    <div>
      <button type="button" onClick={updateData}>update data</button>
      <pre>{JSON.stringify(putData || getData, null, 2)}</pre>
    </div>
  );
};

And here is the test file.

import React from 'react';
import { render, waitForElement, fireEvent } from '@testing-library/react';
import axios from 'axios';
import MockAxios from 'axios-mock-adapter';

import AxiosHooks from './AxiosHooks';

const mock = new MockAxios(axios);

describe.skip('<AxiosHooks />', () => {
  it('should get server time', async () => {
    mock.onGet('/bins/820fc').reply(200, {
      updatedAt: '2019-09-29T04:46:23.256Z',
    });
    const { getByText } = render(<AxiosHooks />);

  // Failed! It will get now time.
    await waitForElement(() => getByText('2019-09-29T04:46:23.256Z'));
  });

  it('should get updated server time', async () => {
    mock.onGet('/bins/820fc').reply(200, {
      updatedAt: '2019-09-29T04:46:23.256Z',
    });
    mock.onPut('/bins/820fc').reply(200, {
      updatedAt: '2019-09-29T04:46:30.256Z',
    });
    const { getByText } = render(<AxiosHooks />);
    const updateButton = await waitForElement(() => getByText('update data'));

    fireEvent.click(updateButton);

    // Failed! It will get now time.
    await waitForElement(() => getByText('2019-09-29T04:46:30.256Z'));
  });
});

SSR does not work

Hello there, thank you very much for the efforts put into this so far.

I played with this library today and I am puzzled if this actually works on the server-side. I'll explain what I tried so far. Perhaps, I did something wrong. Perhaps, it's an issue with the bundler setup. Perhaps, React is not mature enough to support this functionality.

  1. First, I created a new app with Razzle: https://github.com/jaredpalmer/razzle
  2. Then, I did the configurations for axios-hooks as instructed.
  3. I fetched data from: https://www.mocky.io/v2/5185415ba171ea3a00704eed and added it to the component body

Now the application works well. The component with the hook looks like this:

function Home() {
  const [{data, loading, error}] = useAxios({url: 'https://www.mocky.io/v2/5185415ba171ea3a00704eed'});

  if (loading) return <p>Loading...</p>
  if (error) return <p>Error!</p>

  return (
    <div>
      Home
      {JSON.stringify(data)}
    </div>
  );
}

Then I added a console.log to the static markup generated from the react-dom renderToString method. Sadly, the only thing I see on the server-side is:

<p>Loading...</p>

This gives me the feeling that actual markup with data is never generated on the server-side. Instead, the server-side markup is generated for the loaders, then the actual data hydration happens on the client-side. If that is the case, I think it partially defeats the whole purpose of using server-side rendering.

Happy to discuss/clarify/give more information etc.

Thank you again for all the effort put into this library.

lrucache.load cannot read property 'length' of undefined

I'm getting the error:

index.js:238 Uncaught TypeError: Cannot read property 'length' of undefined
    at LRUCache.load (index.js:238)
    at loadCache (index.js:27)
    at Module../src/client.js (client.js:17)
    at __webpack_require__ (bootstrap:19)
    at Object.0 (client.js:34108)
    at __webpack_require__ (bootstrap:19)
    at bootstrap:83
    at bootstrap:83

I've basically just followed the instructions here

The relevant server code:

const axios = Axios.create({
  baseURL: 'http://localhost:3000'
})
const cache = new LRU({ max: 500 })
configure({axios, cache})
app.get('*', async (req, res) => {
  const markup = renderToString(
    <StaticRouter location={req.url}>
      <App />
    </StaticRouter>
  )
  const cache = await serializeCache()
  console.log(cache)
  
  res.end(`
  <!DOCTYPE html>
  <head>
    <title>Eggshell</title>
    <link type="text/css" rel="stylesheet" href="main.css">
    <meta name="robots" content="noindex, nofollow">
    <script src="/client.js" defer></script>
    <script>
    window.__AXIOS_HOOKS_CACHE__ = ${cache}
    </script>
  </head>
  <body>
    <div id="app">${markup}</div>
  </body>
  `)
})

The relevant client code:

import './style.css'
import {hydrate} from 'react-dom'
import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'

import { App } from './app'
import { loadCache, configure } from 'axios-hooks';
import Axios from 'axios'
import LRU from 'lru-cache'

const axios = Axios.create({
  baseURL: 'http://localhost:3000'
})
const cache = new LRU({ max: 500 })
configure({axios, cache})

loadCache(window.__AXIOS_HOOKS_CACHE__)
delete window.__AXIOS_HOOKS_CACHE__

hydrate(
    <Router>
        <App />
    </Router>
    , document.querySelector('#app')
)

Add documentation on how to best chain requests.

Hello!

I have been looking everywhere and trying to have a go at this myself, but I'm still haven't found a pattern that allows me to chain two axios hooks sequentially. Using vanilla axios I could do something like this:

useEffect(async () => { // ignore the annoying console error for example sake
   const {data: value} = await axios.get('/api/1');
   const {data: value2} = await axios.get(`/api/${value}`);
   setState(value2);
});

however this kind of solution inside of a useEffect is kind of meh, since I loose all the goodies from axios-hooks. These are the functionalities from axios-hooks i want to keep leveraging:

  • not having to keep track of loading and error state myself
  • using the cache of useAxios, instead of adding yet another library to the project

The problems i'm facing are:

  • No ability to await getValueOne and call getValueTwo immediatly after
  • between the two requests there is a gap where nothing is loading which causes my application to flash my compoment before all data as loaded. i fixes this with another loading state as seen in the example

Here is my current implementation of a 2 sequential axios hooks calls:

export default (valueZero: string): ResponseValues<string> => {
  // Gaps the bridge between the first call finishing and the second starting
  const [loading, setLoading] = useState(false);

  const [{
    data: valueOne,
    error: errorOne,
    loading: loadingOne,
  }, getValueOne] = useAxios(`/api/${valueZero}`, {manual: true});

  const [{
    data: valueTwo = '',
    error: errorTwo,
    loading: loadingTwo,
  }, getValueTwo] = useAxios(`api/${valueOne}`, {manual: true});

  useEffect(function getFirstValue() {
    if (valueZero) {
      setLoading(true);
      getValueOne(undefined, {useCache: true});
    }
  }, [valueZero, getValueOne]);

  useEffect(function getSecondValue() {
    if (valueTwo) {
      setLoading(false);
      getValueTwo(undefined, {useCache: true});
    }
  }, [valueOne, getValueTwo]);

  // wrapping it as a ResponseType for convenience ;)
  return {
    data: valueTwo,
    error: errorOne || errorTwo,
    loading: loading || loadingOne || loadingTwo,
  };
};

This is incredibly ugly and I was hoping we could brainstorm a bit here to come up with a better alternative to my approach. My motivations to want to keep axios-hooks and not use axios only are:

Any ideas how can we make this better?

Cache is not working

I tried to use the cache and this is not working for me.

I attached the index.js and App.js and the versions from packages that I am using.

I put this in index.js

const axios = Axios.create({
baseURL: 'https://api.myjson.com/',
})

const cache = new LRU({ max: 10 })

configure({ cache, axios })

and the following in App.js

import React, { useState } from 'react';
import './App.css';

import useAxios from 'axios-hooks'

function App() {

const [name, setName] = useState("pablo");

const [{ data, loading, error }, refetch] = useAxios('bins/820fc', { manual: false, useCache:true });

const handleSubmit = event => {
event.preventDefault();
refetch();
}

if (loading) return

Loading...

if (error) return

Error!

return (




Enter your name:
<input
id="name"
type="text"
value={name}
onChange={e => setName(e.target.value)}
/>
Submitss

{JSON.stringify(data, null, 2)}



);
}

export default App;

and I am using the following versions:

"axios": "^0.19.0",
"axios-hooks": "^1.9.0",
"lru-cache": "^5.1.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",

useAxiosCache

Thanks for you great work!!

SSR: Isolate clients

Looks like there is no isolation between clients.

All promises will be pushed to the one array:

const ssrPromises = []

So, there is unexpected behavior when multiple requests will be received.

const cache = await serializeCache() will wait for promises created by different requests.

Is it possible to specify the shape of params object?

Hello,
I'm recently using TypeScript and axios-hooks a lot and I was wondering:

is there a way to constraint the params with an interface or a type?

Actually, with axios-hooks it is possible to specify an interface for the response like that:

interface ApiResponse {
   total: number;
   todos: string[];
}

useAxios<ApiResponse>()

I was thinking about something like that:

interface ApiRequestParameters {
    title: string;
    author: string;
}

interface ApiResponse {
   total: number;
   todos: string[];
}

const [, fetchTodos] = useAxios<ApiRequestParameters, ApiResponse>({}, {
   manual: true
})

Doing so we can have a nice error in situations like this:

fetchTodos({
    title: 'Foo',
   author: 'Bar',
   // This should give an error, as `sort` is not in `ApiRequestParameters` `interface`
   sort: 'newest'
})

What do you think?

Feature request: fetchPolicy

I'm running into a scenario where I could benefit from something similar to Apollo's fetchPolicy: https://www.apollographql.com/docs/react/api/react-apollo/

Specifically, the cache-and-network variant is the most useful to me, where I want to load data from the cache, but also make a network request to fetch potential updates.

Do you think it's possible to add an option like this? Ideally, it's something you could configure globally as part of configure, but also override on a per-hook basis.

UnhandledPromiseRejectionWarning on Server side

If I use useAxios on nextjs server side, if the call returns an error, an unhandled promise error will occur.
Is there any error handling in the execution of the ssrPromises array?

(node:73458) UnhandledPromiseRejectionWarning: Error: Request failed with status code 401
    at createError (/Users/mk/dev/workspace/dapps/gione/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/Users/mk/dev/workspace/dapps/gione/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/Users/mk/dev/workspace/dapps/gione/node_modules/axios/lib/adapters/http.js:237:11)
    at IncomingMessage.emit (events.js:215:7)
    at IncomingMessage.EventEmitter.emit (domain.js:476:20)
    at endReadableNT (_stream_readable.js:1183:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
(node:73458) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 7)
(node:73458) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

TypeScript Support

Are there any plans for TypeScript support or at least just a definitions file for now?

How should we handle errors on manual requests?

Thanks for the library!

I have a question around this example:

import useAxios from 'axios-hooks'

function App() {
  const [{ data: getData, loading: getLoading, error: getError }] = useAxios(
    'https://api.myjson.com/bins/820fc'
  )

  const [
    { data: putData, loading: putLoading, error: putError },
    executePut
  ] = useAxios(
    {
      url: 'https://api.myjson.com/bins/820fc',
      method: 'PUT'
    },
    { manual: true }
  )

  function updateData() {
    executePut({
      data: {
        ...getData,
        updatedAt: new Date().toISOString()
      }
    })
  }

  if (getLoading || putLoading) return <p>Loading...</p>
  if (getError || putError) return <p>Error!</p>

  return (
    <div>
      <button onClick={updateData}>update data</button>
      <pre>{JSON.stringify(putData || getData, null, 2)}</pre>
    </div>
  )
}

If there is an error calling executePut then we could end up with the following error

createError.js:17 Uncaught (in promise) Error: Request failed with status code 500
    at createError (createError.js:17)

This does not show if I use

      data: {
        ...getData,
        updatedAt: new Date().toISOString()
      }
    }).catch(() => {})

I was not expecting an error to be thrown, as the hook sets the error. Is this how I should handle this error, or am I doing something wrong?

Feature request: initial data

I love this library, thanks for sharing!
One thing that I think would be very helpful is if the useAxios hook accepted an option for initial data with which to populate the request.

For example, let's say I have a request that returns an array of objects, from which I am generating a table. I currently need to do something like:

const [req] = useAxios('...')
return (
  <table>
    <tbody>
      { (req.data || []).map((r, i) => <tr key={i}>...</tr>) }
    </tbody>
  </table>
)

It would be nice if I could do something like const [req] = useAxios('...', { initialData: [] }) in the example above so that I don't have to handle the case where req.data is undefined.

If you like this idea, but not enough to bother implementing it yourself, let me know and I'll make time to send a PR.

Thanks!

Doesn't wait for data before rendering

I might be missing something but from reading the example and code these hooks don't actually allow you to render your data server side. Yes, you can render the state of your app before you have data and these hooks will allow you to wait for data being fetched serialized to the client. However in order to achieve SEO goals you have to have the data rendered within your html.

In graphql-hooks-ssr they make a pass through the app render tree with renderToStaticMarkup. That is what queues up the async requests. They then wait for those async requests to finish and then make another render pass with renderToString with your pre-loaded data.

Question: how to execute code after getting a response?

I am beginner developer and this might be a dumb question. All I want is to call a function after getting a response.
My current solution is to use useEffect:

useEffect(() => {
    if (!postLoading) {
        // Calling my function
    }
}, [postLoading]);

I don't know if that is a good way or not, but I would prefer to do it something like this:

executePost({
    data: {
        // My data
    }
}).then( /*Calling my function*/);

The second solution in VS Code spits out error "Property 'then' does not exist on type 'void'.".
Is there a way to do this with axios hooks?

Multiple axios instances

Hello @simoneb ,
is there a way to use multiple axios instances?
As far as I understand, configure accept a single instance.
Is there something I'm missing or is this funcionality not present ATM?
Is it going to be possible?
Maybe something like:

import { configure } from 'axios-hooks'
import Axios from 'axios'

const firstInstance= Axios.create({
  baseURL: 'https://api.myjson.com/'
})

const secondInstance= Axios.create({
  baseURL: 'https://api.myjson.com/'
})

configure({ firstInstance, secondInstance })
//OR
//configure({axios: [firstInstance, secondInstance]})

(In either cases defaults to firstInstance if not specified)

and then use it like that:

import useAxios from 'axios-hooks'

const [{ data: getData, loading: getLoading, error: getError }, manualFetch] = useAxios(
    'bins/820fc',
    {
         manual: true,
         instance: 'firstInstance'
    }
  )

This is my general idea.
Do you think that something along the lines of that is possible to achieve?
Thank you for your time!

Dependency Dashboard

This issue contains a list of Renovate updates and their statuses.

Pending Status Checks

These updates await pending status checks. To force their creation now, check the box below.

  • chore(deps): update dependency @types/react-dom to v17.0.5

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.


  • Check this box to trigger a request for Renovate to run again on this repository

CancelToken property not available in custom axios instance

After latest update related to the CancelToken, there is an issue with:

cancelSourceRef.current = axiosInstance.CancelToken.source()

Everything works when you use AxiosStatic, imported directly from `axios.
But when you pass your own instance through the options, like:

configure({
  axios: axios.create({
    baseURL: theme.config.api.endpoint,
  }),
});

it is AxiosInstance used which doesn't contain CancelToken property anymore and it ends up with the following error in mentioned line:

TypeError: Cannot read property 'source' of undefined

Conditional caching

Requested in #233, the useCache option could be extended to conditionally use cache based on user logic.

How to deal with errors? Not presenting error information.

Axios has an error.response object that mirrors the information present when the server returns a normal response:

{
  data: ...
  status: ...
  statusText: ...
  headers: ...
  config: ...
}

I would like to have access to this information, but when const [{ data, loading, error, response }, fetch] = useAxios(...) returns an error from the server, the data and response come with the previously correct response values (undefined if it was the first request made).

Shouldn't it update the data, or at least the response with the axios' error.reponse value? Or at least construct the useAxios()'s error according to that value? Or am I missing the point completely and useAxios() is meant to be used differently when handling errors?

Right now, to know the status of the error, I have to extract the number part from the string associated with useAxios()'s error value: Error: Request failed with status code 404

execute/refetch should be async

I would like the ability to await refetch/execute and receive the response data in return.

const data = await execute()
// ... use data here

Suggested approach for PUT/PATCH/POST

This package is great - thank you!

Do you have a suggested approach for mutations? Maybe something like usePost or usePut, which might return a function/promise.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

how to chain promise action?

I have two async requests,and one depend on the result of the other request:

const [{ data = {}, loading }] = useAxios({
    url: '/url1',
    params: { id },
  })

the next request need the value of data,so I need to write like this:

const [ ,findNext] = useAxios({
    url: '/url2',
  }, {
  manual: true
})

  useEffect(() => {
    if (data.code) {
      findNext({code: data.code})
    }
  }, [data])

this works,but it feels very ugly。I prefer the chained promise way,so do you have any advice, or
just write the normal useState way?

@simoneb

pass params to execute

Hello, is there a way to pass params throw the execute/refetch function ?
if not I think this should be added.

const [{ data, loading, error }, getUser] = useAxios(
    'https://api.github.com/search/users?q=${username}',
    {
      manual: true
    }
);

I needed to pass username to the API url

<SearchBar
    onSearch={username => getUser(username)}
/>

thank you for creating this by the way

Interceptors?

how to add interceptors?

axios.interceptors.request.use((config) => {
        try {
            let token = localStorage.getItem('token');

            let locale = getGlobalLocale();

            if (token) {
                config.headers['Authorization'] = 'Bearer ' + token
            }
            if (locale.currency) {
                config.headers['currency'] = locale.currency;
            }

            return config;
        } catch (e) {
            // console.log(e);
        }

});

Reports the error ' Can't perform a React state update on an unmounted component'

index.js:1375 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    in TestComponent (at App.js:23)
Uncaught (in promise) Cancel {message: undefined}

Example here test-axios-hook.zip, to use the example:

  1. Run the example
  2. In Chrome devtools click Network, and set the Throttling to 'Slow 3G'
  3. Click 'Reload' and before it completes click 'Hide'

You'll then get the following error:
image

Feature request: Don't request the same query twice while in flight

I imagine this will be a bit complicated to implement, and is likely outside the scope of the library, but I figured I'd ask.

I'm working with a scenario where I would like to render an <Avatar /> component which uses a useAxios hook within it to fetch information about the user. When rendering the same person's man times on a single page, it issues a request for each one.

Do you think it would be possible to have subsequent requests wait for the initial request to resolve?

Uncaught Error during jest testing

When I try to test the network failure case I get a thrown error without being caught which breaks my test, when I replaced axios-hooks with the original axios library and a catch block on each request the tests passed smoothly
I believe the issues is throwing an error in the catch block

async function request(config, dispatch) {
    try {
      dispatch({ type: actions.REQUEST_START })
      const response = await axiosInstance(config)
      dispatch({ type: actions.REQUEST_END, payload: response })
      return response
    } catch (err) {
      if (StaticAxios.isCancel(err)) {
        return
      }

      dispatch({ type: actions.REQUEST_END, payload: err, error: true })
      
        That =>  throw err
    }
  }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.