reactjsmaterial-uimui-autocomplete

How do I get my options to display with Autocomplete (Material UI)?


I'm trying to help my friend figure out why Autocomplete isn't showing anything. Below is the code:

var names = [];
const schoolList = async () => ( await axios.get("http://localhost:5000/api/grabUnivNames/")
    .then((res) => {

      // schoolList =  JSON.stringify(res.data.msg)
      names = res.data.msg.map(user => user.school_name);;
      console.log(names)
      // return res.data.msg.map(user => user.school_name);
    })
    .catch((error) => {
      console.log("ERROR");
      console.log(error);
    })
  );
schoolList();

return() with Autocomplete:

        <Autocomplete
            options={names}
            sx={{ width: 300 }}
            renderInput={(params) => <TextField {...params} label="School Name" />}
          />

What names contains:

enter image description here

What shows:

enter image description here

I only started learning about Autocomplete today but I think the problem may be in how he is obtaining names or how names is formatted but I am also very unfamiliar with Autocomplete.

How can I get names to display on the dropdown?


Solution

  • first of all i am assuming that your data fetching is done correctly and you use react functional based components. You will need 2 main requirements to achieve what you want

    1. first of all replace normal variable names with useState hook of names array and loading boolean, cause normal variables will not have dynamic values over multiple renders
    2. MUI Autocomplete supports async operation , so you will attach the getSchoolList handler to onOpen prop, and loading prop so let the component show progress while loading
    const [names,setNames] = React.useState([])
    const [loading, setLoading] = React.useState(false)
    const getSchoolList = () => {
    setLoading(true)
    axios.get("http://localhost:5000/api/grabUnivNames/")
        .then((res) => {
    
          // schoolList =  JSON.stringify(res.data.msg)
          const namesArr = res.data.msg.map(user => user.school_name)
          setNames(namesArr)
          // return res.data.msg.map(user => user.school_name);
        })
        .catch((error) => {
          console.log("ERROR");
          console.log(error);
        }).finally(() => setLoading(false))
    }
    
    <Autocomplete
                options={names}
                onOpen={() => getSchoolList()}
                loading={loading}
                sx={{ width: 300 }}
                renderInput={(params) => <TextField {...params} label="School Name" />}
              />