Home  >  Q&A  >  body text

"How to enable MUI Autocomplete's onChange event to update the value"

I am getting the autocomplete options from the API and it is getting it perfectly and also showing the selected option returned from the API but the problem I am facing is that no matter I try to remove or add a value (category), It won't remove or add anything.

Online Demo Codesandbox

PostInfo.jsx:

import SelectPostsCatsOptions from "../../components/autocomplete/SelectPostsCatsOptions";
import postInfo from "./postInfo.json";
export default function PostInfo() {
  const [categories, setCategories] = useState([]);
  const [selectedCategories, setSelectedCategories] = useState([]);

  useEffect(() => {
    const getPost = async () => {
      try {
        setCategories(postInfo[0].categories);
        setSelectedCategories(postInfo[0].categories);
      } catch (err) {}
    };
    getPost();
  });

  return (
   
    <div className="PostInfoPage">
      <>
        <div>
          <form>
            <div>
              <h3>帖子类别:</h3>
              <SelectPostsCatsOptions
                selectedCategories={selectedCategories}
                setSelectedCategories={setSelectedCategories}
                onChange={(event, newSelectedCategories) =>
                  setSelectedCategories(newSelectedCategories)
                }
                value={selectedCategories}
              />
              <p>已选择的类别:</p>
            </div>
          </form> 
        </div>
      </>  
    </div>
  );
}

Select PostsCatsOptions:

import categories from "./postsCategories.json";

export default function SelectPostsCatsOptions({
  selectedCategories,
  setSelectedCategories,
  onChange,
  value
}) {
  return (
    <div>
      <Autocomplete
        id="categories"
        disablePortal
        multiple
        getOptionLabel={(category) => category.catName}
        options={categories}
        disableGutters
        isOptionEqualToValue={(option, value) =>
          option.catName === value.catName
        }
        renderOption={(props, categories) => (
          <li {...props} key={categories.id}>
            {categories.catName}
          </li>
        )}
        renderTags={(value, getTagProps) =>
          value.map((option, index) => (
            <Chip
              key={option.id}
              label={option.catName}
              {...getTagProps({ index })}
            />
          ))
        }
        renderInput={(params) => (
          <TextField {...params} placeholder="类别" />
        )}
        value={value}
        onChange={onChange}
      />
    </div>
  );
}

I don't know what I'm missing here, why I can't add or remove a tag from autocomplete!

P粉649990273P粉649990273421 days ago707

reply all(1)I'll reply

  • P粉512526720

    P粉5125267202023-09-16 14:02:30

    Update your useEffect dependency array. https://legacy.reactjs.org/docs/hooks-effect.html []means only called when mounting

    It will be called on every render

      useEffect(() => {
        const getPost = async () => {
          try {
            setCategories(postInfo[0].categories);
            setSelectedCategories(postInfo[0].categories);
          } catch (err) {}
        };
        getPost();
      }, []); //<--- 改变
    

    reply
    0
  • Cancelreply