1
votes

I'm trying to create an autocomplete field that fetches the options from the components state (the state fetches it from the backend). This is my component:

export const Person: React.FC<PersonProps> = ({name, avatar, setMainState}: PersonProps) => {
  const [location, setLocation] = useState('');
  const [options, setOptions] = useState([]);
  const change = (event: any) => {
    setLocation(event.target.value)
    setMainState(event.target.value)
  }
  
  useEffect(() => {
    axios
      .get(`http://localhost:8080/autocomplete/?str=` + location)
      .then(res => {
        setOptions(res.data);
      })
  },[location])

  return <Box display="flex" height="30%">
    <Typography>{name}</Typography>
    <Autocomplete
      id="combo-box-demo"
      options={options}
      getOptionLabel={(option) => option as string}
      style={{ width: 300 }}
      renderInput={(params) => <TextField {...params} label="Combo box" variant="outlined" />}
    />
  </Box>
};

But for some reason, the options array from my state isn't recognized as an array (although I initialized it with an empty array). I get this warning:

index.js:1 Warning: Failed prop type: Invalid prop `options` of type `object` supplied to `ForwardRef(Autocomplete)`, expected `array`.
    in ForwardRef(Autocomplete) (created by WithStyles(ForwardRef(Autocomplete)))
    in WithStyles(ForwardRef(Autocomplete)) (at Person.tsx:56)
    in div (created by Styled(MuiBox))
    in Styled(MuiBox) (at Person.tsx:49)
    in Person (at Main.tsx:14)
    in div (created by Styled(MuiBox))
    in Styled(MuiBox) (at Main.tsx:13)
    in div (created by Styled(MuiBox))
    in Styled(MuiBox) (at Main.tsx:12)
    in Main (at App.tsx:11)
    in div (at App.tsx:10)
    in App (at src/index.tsx:6)

Do you have any idea what could be the cause? Any thoughts would be helpfull:) thanks!

1
Can you console.log(option) after you fetched it? My assumption is that is an object, not an arrayMagofoco
thank you so much! apparently when server returned error, it really was an object. solved!Rotem Linik
No problem! If you are satisfied with the answer, accept it belowMagofoco

1 Answers

1
votes

My assumption is that when you do: setOptions(res.data); you are setting the options to an object, not an array.

In fact the error says: ..."options" of type "object" supplied to "ForwardRef(Autocomplete)", expected "array". So it expects an array but you are providing an object