Search code examples
reactjsobject

Iterate over a nested object and provide as "options" to typeahead component


I'm using react-bootstrap-typeahead component in a project. I have following API response data:

{
  "data": [
    {
      "i": 21,
      "att": {
        "lead": "Rent",
        "city": "bangalore"
             }
    }, 
{
... 
}
... 
  ]
}

How do I fetch the city name and provide to options property of the component? Thanks in advance.

Edit 1:

The code to fetch the api response is:

const [myData, setMyData] = useState();

  async function getCities() {

    return await axios.get(`${API_URL}/api/cp`)

  }
  useEffect(() => {

    getCities().then((response) => setMyData(response))
    console.log(myData)

  }, [props])

Edit 2:

async function getCities() {

    const dataOut = await axios.get(`${API_URL}/api/cprops`)

    return dataOut.data

  }
  useEffect(() => {

    getCities().then((response) => setMyData(response))
    console.log(myData)

  }, [props])

Here is the updated code for fetching data


Solution

  • Thanks all for your help. I was able to implement the following solution:

    const getData = async () => {
        const response = await axios.get(
          `${API_URL}/api/cprops` 
        );
        setMyData(response)  };
    

    This method is called after the dropdown option is selected. Code :

     const handleDropdownChange = (selectedOption) => {
        setSelectedOption(selectedOption);
        getData();
      };
    

    The options paramter:

    options = [
     myData.data.map((item) => {
       {(item.attributes.city)}
          
         })
       ]
    

    The component:

               <Typeahead
             
                onChange={(selected) => {
                  setSelectedLoc(selected)
                }}
               options = {options}
                placeholder="City"
              />