simoneb / axios-hooks Goto Github PK
View Code? Open in Web Editor NEW🦆 React hooks for axios
License: Other
🦆 React hooks for axios
License: Other
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?
Hey, great library!
Do you have a pagination example?
I'm trying to setup Laravel pagination.
Thanks
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: [] }
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.
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 😅.
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?
If you make a request and it returns an error, and then make a new request, it won't reset error.
I think it's just a matter of resetting error
during REQUEST_START
.
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 ?
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:
useAxios
(with my proposal I can simply change my jest.spyOn(axios, 'get')
to jest.spyOn(axios, 'request')
.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 🙏
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!
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.
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
}
});
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.
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()
}
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!
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?
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
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?
// 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'));
});
});
Ok, this is not an issue with the library, it's a question on how it can be mocked when using it in a React component. I'm using TypeScript which appears to be further complicating the matter (for me anyhow!)
I've created a question on StackOverflow too as can be seen here.
I'd have thought this would be trivial but am finding it tricky!
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.
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.
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')
)
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:
The problems i'm facing are:
await getValueOne
and call getValueTwo
immediatly afterHere 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?
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
if (error) return
return (
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",
Thanks for you great work!!
Looks like there is no isolation between clients.
All promises will be pushed to the one array:
Line 14 in 2c4f0e8
So, there is unexpected behavior when multiple requests will be received.
const cache = await serializeCache()
will wait for promises created by different requests.
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?
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.
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.
Are there any plans for TypeScript support or at least just a definitions file for now?
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?
In the https://github.com/simoneb/axios-hooks#api-1 section the "The error value" link has a typo in the url and leads to https://github.com/axios/.axios#handling-errors instead of https://github.com/axios/axios#handling-errors
thx for this library!
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!
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.
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?
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!
This issue contains a list of Renovate updates and their statuses.
These updates await pending status checks. To force their creation now, check the box below.
These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.
After latest update related to the CancelToken
, there is an issue with:
Line 148 in 307c7c1
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
Requested in #233, the useCache option could be extended to conditionally use cache based on user logic.
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
Please add documentation for implementing onUploadProgress so developers can use upload percentage indicators
Any way to receive the current Progress and then attach it to a Progress Bar o something like that?
Thank you!
I would like the ability to await refetch/execute and receive the response data in return.
const data = await execute()
// ... use data here
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.
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.
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?
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
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);
}
});
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:
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?
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
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.