I want to implement a field using <AutoComplete />
in my form. I get the options
from a get
request. And here is the result when I print them in console.
[
{
"uid": "c34bb0ed-9f63-4803-8639-a42c7e2a8fb0",
"tag_name": "Food"
},
{
"uid": "346ab2da-e71d-4449-822e-e4836caa7076",
"tag_name": "Religion"
},
{
"uid": "9b4a9fd5-28fd-4690-8b00-a22c08a7c076",
"tag_name": "Culture"
},
{
"uid": "7889048e-03d7-4637-9fee-b22f8e7368dd",
"tag_name": "Nature"
},
{
"uid": "b3809713-b1bc-4676-beec-7637f4ae9183",
"tag_name": "Native people"
},
{
"uid": "1d84d7a2-13f4-43cd-9b8c-666a68d269d6",
"tag_name": "My Host"
}
]
But after I click on any of the checkboxes, the item would be disappeared from the select list.
And also when I see the logs, it seems that the onChange
method does not work correctly, and the first checked value is not set in selectedTags
list.
Here is my code for loading tags:
const [tags, setTags] = useState([]);
const loadTags = async () => {
axios({
method: "get",
url: "http://127.0.0.1:8000/api/v1/blog/tags/",
headers: {
'Content-Type': 'application/json',
}
}).then((result) => {
setTags(result.data.data);
console.log("********** The Tags are ******** ", tags);
}).catch((error) => {
toast.error("Something went wrong while fetching tags.")
})
}
useEffect(() => {
loadTags();
}, []);
Here is my code for AutoComplete
field:
const handleTagSelection = (value) => {
console.log("********** The value is: ***********", value);
setSelectedTags(value);
console.log("++++++++ The selected tags are: ++++++++", selectedTags);
}
<Autocomplete
clearIcon={false}
multiple
id="tags-outlined"
isOptionEqualToValue={(option, value) => option.tag_name === value.tag_name}
options={tags}
getOptionLabel={(option) => option.tag_name}
filterSelectedOptions
sx={{ width: "50rem" }}
size="small"
disableCloseOnSelect
value={selectedTags}
noOptionsText="No related tag is available"
onChange={(e, value) => {
if (value) {
handleTagSelection(value);
} else {
return;
}
}}
renderOption={(props, option, { selected }) => (
<li {...props}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={
selected
}
/>
{option.tag_name}
</li>
)}
style={{ width: 500 }}
renderInput={(params) => (
<TextField {...params} label="Tags" />
)}
/>
I will be grateful for your help.