How to convert a array object to use with MUI's Autocomplete field

Viewed 24

I'm trying to convert my incoming object into something usable by MUI's Autcomplete object, however, I'm struggling to do this.

The code I have currently is as follows:

const [contactList, setContactList] = useState([]);

useEffect(() => {
        fetch(CONTACTS_URL, {
            method: "GET",
            headers: {"Authorization": sessionStorage.getItem("accessToken")}
        })
        .then((response) => response.json())
        .then((responseData) => {
            setContactList({responseData});
        })
        .catch((error) => console.error(error));
    }, [])

Which produces the following when printed to console:

Object
    responseData: Array(1)
        0: 
            {
                contactId: 1, 
                contactName: 'Cool Contact',
                firstLetter: "C"
            }
     length: 1
     [[Prototype]]: Array(0)
     [[Prototype]]: Object

The docs for Autocomplete say I need to do this:

const options = top100Films.map((option) => {
    const firstLetter = option.title[0].toUpperCase();
    return {
      firstLetter: /[0-9]/.test(firstLetter) ? '0-9' : firstLetter,
      ...option,
    };
});

<Autocomplete
      id="grouped-demo"
      options={options.sort((a, b) => -b.firstLetter.localeCompare(a.firstLetter))}
      groupBy={(option) => option.firstLetter}
      getOptionLabel={(option) => option.title}
      sx={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="With categories" />}
/>

However, the example above is under the impression you're using an already pre-defined constant, whereas mine is not quite like that.

How would I go about converting mine into something that can be used by Autocomplete?

1 Answers

Just pass contactList to the options prop, and provide a callback for getOptionLabel.

And, instead of calling setContactList with an object, just pass the array directly. That way, contactList is an array of options.

  const [contactList, setContactList] = useState([]);

  useEffect(() => {
    fetch(CONTACTS_URL, {
      method: 'GET',
      headers: { Authorization: sessionStorage.getItem('accessToken') },
    })
      .then((response) => response.json())
      .then((responseData) => {
        setContactList(responseData);
      })
      .catch((error) => console.error(error));
  }, []);

  return (
    <Autocomplete
      options={contactList}
      getOptionLabel={(contact) => contact.contactName}
    />
  );
Related