useRequest
Custom React Hook for data fetching
Installation
npm install use-request
Usage example
import React, { useState, useCallback } from 'react';
import axios from 'axios';
import { Formik, Form, Field } from 'formik';
import { useRequest } from 'use-request';
function App() {
const [searchValue, setValue] = useState('');
const fetchPeople = useCallback(
() =>
axios
.get(`https://swapi.co/api/people/?search=${searchValue}`)
.then(({ data: { results } }) => results),
[searchValue]
);
const handleSubmit = useCallback(({ inputValue }) => setValue(inputValue), [setValue]);
const [{ isLoading, data, error }, updateData] = useRequest(fetchPeople);
return (
<React.Fragment>
<Formik initialValues={{ inputValue: '' }} onSubmit={handleSubmit}>
<Form>
<Field type="inputValue" name="inputValue" />
<button type="submit">Submit</button>
<button onClick={updateData}>update data</button>
</Form>
</Formik>
{data.map(item => <p>{item.name}</p>)}
</React.Fragment>
);
}
export default App;