Home > Net >  Unable to run autocomplete with JSON input
Unable to run autocomplete with JSON input

Time:07-10

I am using MUI aocomplete component. I have called an API call and feeding 'options' and 'value' with API response. Following is the code.

// App.js

import { useEffect, useCallback, useState } from "react";

import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

function App() {
  const [getUsers, setUsers] = useState([]);

  const fetchUsers = useCallback(async () => {
    try {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );
      const userData = await response.json();
      setUsers(userData);
    } catch (error) {
      console.log("Error in catch!")
    }
  }, []);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);
  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={getUsers.name} // should display dropdown options
      renderInput={(params) => {
        return <TextField {...params} />
      }}
      value={getUsers.id} // value for each dropdown item
    />
  )
}

export default App;

I am getting the following error.

Warning: Failed prop type: The prop `options` is marked as required in `ForwardRef(Autocomplete)`, but its value is `undefined`.

Here is codesandbox link

CodePudding user response:

You need to loop the options because you are retrieving an array, you can do that by using map

options={getUsers.map(el => el.name)} 

Here is the sandbox

import { useEffect, useCallback, useState } from "react";

import TextField from "@mui/material/TextField";
import Autocomplete from "@mui/material/Autocomplete";

function App() {
  const [getUsers, setUsers] = useState([]);

  const fetchUsers = useCallback(async () => {
    try {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );
      const userData = await response.json();
      // console.log("userData: ", userData);
      setUsers(userData);
    } catch (error) {
      console.log("Error in catch!");
    }
  }, []);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);
  return (
    <Autocomplete
      disablePortal
      id="combo-box-demo"
      options={getUsers.map(el => el.name)}
      renderInput={(params) => {
        return <TextField {...params} />;
      }}
      value={getUsers.id}
    />
  );
}
  • Related