在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:simoneb/axios-hooks开源软件地址:https://github.com/simoneb/axios-hooks开源编程语言:JavaScript 99.5%开源软件介绍:
axios-hooksReact hooks for axios, with built-in support for server side rendering. Features
Installation
Quick Startimport useAxios from 'axios-hooks'
function App() {
const [{ data, loading, error }, refetch] = useAxios(
'https://reqres.in/api/users?delay=1'
)
if (loading) return <p>Loading...</p>
if (error) return <p>Error!</p>
return (
<div>
<button onClick={refetch}>refetch</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)
} DocumentationAPIExamples
Guides
APIThe package exports one default export and named exports: import useAxios, {
configure,
loadCache,
serializeCache,
makeUseAxios
} from 'axios-hooks' useAxios(url|config, options)The main React hook to execute HTTP requests.
Returns
configure({ cache, axios, defaultOptions })Allows to provide custom instances of cache and axios and to override the default options.
serializeCache()Dumps the request-response cache, to use in server side rendering scenarios. Returns
loadCache(cache)Populates the cache with serialized data generated by
makeUseAxios({ cache, axios, defaultOptions })Creates an instance of the
Returns An instance of The returned value, besides being a function that can be used as a React Hook, also contains the properties:
which are the same as the package's named exports but limited to the Refresh BehaviorThe arguments provided to When they change, if the configuration allows a request to be fired (e.g. Because of this, it's important to make sure that the arguments to ConfigurationUnless provided via the
These defaults may not suit your needs, for example:
In such cases you can use the
Exampleimport { configure } from 'axios-hooks'
import LRU from 'lru-cache'
import Axios from 'axios'
const axios = Axios.create({
baseURL: 'https://reqres.in/api'
})
const cache = new LRU({ max: 10 })
configure({ axios, cache }) Manual RequestsOn the client, requests are executed when the component renders using a React This may be undesirable, as in the case of non-GET requests. By using the ExampleIn the example below we use the import useAxios from 'axios-hooks'
function App() {
const [{ data: getData, loading: getLoading, error: getError }] = useAxios(
'https://reqres.in/api/users/1'
)
const [
{ data: putData, loading: putLoading, error: putError },
executePut
] = useAxios(
{
url: 'https://reqres.in/api/users/1',
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>
)
} Manual CancellationThe cancellation method can be used to cancel an outstanding request whether it be
from the automatic hook request or from the ExampleIn the example below we use the function App() {
const [pagination, setPagination] = useState({})
const [{ data, loading }, refetch, cancelRequest] = useAxios({
url: '/users?delay=5',
params: { ...pagination }
})
const handleFetch = () => {
setPagination({ per_page: 2, page: 2 })
}
const externalRefetch = async () => {
try {
await refetch()
} catch (e) {
// Handle cancellation
}
}
return (
<div>
<button onClick={handleFetch}>refetch</button>
<button onClick={externalRefetch}>External Refetch</button>
<button disabled={!loading} onClick={cancelRequest}>
Cancel Request
</button>
{loading && <p>...loading</p>}
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)
} Server Side Rendering
How it works
Example<!-- fragment of the HTML template defining the window global variable -->
<script>
window.__AXIOS_HOOKS_CACHE__ = {{{cache}}}
</script> // server code for the server side rendering handler
import { serializeCache } from 'axios-hooks'
router.use(async (req, res) => {
const index = fs.readFileSync(`${publicFolder}/index.html`, 'utf8')
const html = ReactDOM.renderToString(<App />)
// wait for axios-hooks HTTP requests to complete
const cache = await serializeCache()
res.send(
index
.replace('{{{html}}}', html)
.replace('{{{cache}}}', JSON.stringify(cache).replace(/</g, '\\u003c'))
)
}) // client side code for the application entry-point
import { loadCache } from 'axios-hooks'
loadCache(window.__AXIOS_HOOKS_CACHE__)
delete window.__AXIOS_HOOKS_CACHE__
ReactDOM.hydrate(<App />, document.getElementById('root')) Multiple Hook InstancesSometimes it is necessary to communicate with different APIs or use different caching strategies for different HTTP interactions.
In other words,
Exampleimport axios from 'axios'
import { makeUseAxios } from 'axios-hooks'
const useAxios = makeUseAxios({
axios: axios.create({ baseURL: 'https://reqres.in/api' })
})
function App() {
const [{ data, loading, error }, refetch] = useAxios('/users?delay=1')
if (loading) return <p>Loading...</p>
if (error) return <p>Error!</p>
return (
<div>
<button onClick={refetch}>refetch</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
)
} Promisesaxios-hooks depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can polyfill. Credits
LicenseMIT |
2022-08-15
2022-08-17
2022-09-23
2023-10-27
2022-08-18
请发表评论