I'm trying to make a search component with Material-UI Autocomplete.
The issue I am facing is that the data from the API doesn't reload. So when I load, it fetch results, but then, if I change the input, it doesn't make another request.
I tried calling the api function in the onChange function, but it still doesn't do anything.
I am still new to React Hooks, any feedback will be greatly appreciated.
import fetch from "cross-fetch";
import React from "react";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";
import CircularProgress from "@material-ui/core/CircularProgress";
function sleep(delay = 0) {
return new Promise((resolve) => {
setTimeout(resolve, delay);
});
}
export default function Asynchronous() {
const [open, setOpen] = React.useState(false);
const [options, setOptions] = React.useState([]);
const [input_var, setInput] = React.useState("");
const loading = open && options.length === 0;
const api = React.useEffect(() => {
let active = true;
if (!loading) {
return undefined;
}
(async () => {
var response = await fetch(`${baseUrl}/users?q=${input_var}`, {
method: "get",
headers: {
"Content-Type": "application/json",
Authorization: auth
}
});
await sleep(1e3); // For demo purposes.
const countries = await response.json();
console.log(countries);
countries.items.map((item) => console.log(item.name));
if (active) {
setOptions(countries.items);
}
})();
return () => {
active = false;
};
}, [loading, input_var]);
React.useEffect(() => {
if (!open) {
setOptions([]);
}
}, [open]);
return (
<Autocomplete
id="asynchronous-demo"
style={{ width: 300 }}
open={open}
onOpen={() => {
setOpen(true);
}}
onClose={() => {
setOpen(false);
}}
getOptionSelected={(option, value) => option.name === value.name}
getOptionLabel={(option) => option.name}
options={options}
loading={loading}
renderInput={(params) => (
<TextField
{...params}
label="Asynchronous"
variant="outlined"
onChange={async (newValue) => {
await api;
await setInput(newValue);
}}
InputProps={{
...params.InputProps,
endAdornment: (
<React.Fragment>
{loading ? (
<CircularProgress color="inherit" size={20} />
) : null}
{params.InputProps.endAdornment}
</React.Fragment>
)
}}
/>
)}
/>
);
}