0

I need to get list of keys from firebase database and load list of keys in to dropdown menu in reactjs. I am using Axios to get firebase data.

Instance.js

import axios from 'axios'
export default axios.create({
    baseURL:'https://boncafe-xxxx.firebaseio.com/'

})

I this is how I get data.

 instance.get('/Catagory.json')
        .then(response=>{

            console.log(response.data);
})
}

But I want to save only List of keys from above results and load them to dropdown menu.

Ishara96
  • 25
  • 5
  • What's the problem? If you're wondering how to access the data in your `render` function, you'd store it in the component's state for that. See https://stackoverflow.com/questions/59871401/how-to-update-firebase-data-to-the-react-application-in-realtime/59871491#59871491 – Frank van Puffelen Jun 02 '20 at 13:01
  • I get list of objects from above method. now I need to save only list of keys from all objects in array. – Ishara96 Jun 03 '20 at 06:57

1 Answers1

0

declare array in State to hold data

this.State{
     category:[],  // to keep fetched data from database
     selectedCategory: "", // to keep selected item from dropdown
}

Load data in to array

 instance.get('/Catagory.json')
    .then(response=>{

        console.log(response.data);
        const fetchedResult=[];
        for(let key in response.data){
            fetchedResult.unshift(
                {
                    ...response.data[key],
                    id:key
                }
            )

        }
    this.setState({category:fetchedResult})

 })

In render() method write code to display dropdown menu.

<div>

       <label>Select Item </label>
          <select value={this.state.selectedCategory} 
          onChange={e => this.setState({selectedCategory: e.target.value})}> //onChange function will set selectedCategoty in State with choosen item
          {this.state.category.map((item) => <option key={item.id} value={item.id}>{item.name} //Name to show in dropdown

          </option>)} //load values to dropdown
          </select>
    </div>

Replace value="item.id" with any property you need to keep as selected item.this value will save as 'selectedcategory'in State.

Replace {item.name} to change text to display at dropdown. ex: {item.color}

Sample JSON

"Vehicle":{
 001{
 "name":"Car"
 "color":"red"
 },

 002{
 "name":"Bus"
 "color":"Yellow"
 },

}
Ishara96
  • 25
  • 5