0

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. enter image description here

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. enter image description here

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.

1 Answers1

1

Remove the filterSelectedOptions attribute from Autocomplete component may help.

Reference: Autocomplete API props

Lynn C.
  • 191
  • 6
  • Thanks. Now the checkbox is checked correctly, but the `onChange` handler still does not work, and has the same problem. And the value is not correctly saved in `selectedTags`. – Aylin Naebzadeh Apr 06 '23 at 09:48
  • 1
    @NarimanMasjedi `onChange` handler does work. The reason why you see wrong value is: When you call `setSelectedTags`, React doesn't immediately update the value of `selectedTags`, but instead pushes the update into React's update queue to be processed later. Therefore, when you log `selectedTags` inside console.log, you see the value before the update. You can use `useEffect` to console log whenever `selectedTags` is updated, it will give you correct answer. – Lynn C. Apr 06 '23 at 15:28
  • @NarimanMasjedi You can check out this [related answer](https://stackoverflow.com/a/66644538). – Lynn C. Apr 06 '23 at 15:31