Sr New
Sr New

Reputation: 77

Accessing data and displaying in a dropdown

I have data as :

Rooms.
Rooms   : {"_id":{"$oid":"46746766474664"},"RoomID":{"$numberInt":"1"},"RoomDesc":"1st Floor"}

I am trying to access and show them in a dropdown.

while mount I am doing this operation.

mongodb.db("TestDB")
            .collection("Rooms")
            .find({}, { limit: 1000 })
            .asArray()
            .then(rooms => {
                this.setState({ rooms });
            });

and in searable dropdown,

   <Dropdown
                                placeholder='Select Rooms'
                                fluid
                                search
                                selection
                                options={this.state.rooms.RoomID}
                                //value={RoomID}
                            />

Its always returning Null no entries. How can I access this data ? should I use Map (or) any other suggestion. Is there a way we can build on console.

From mongodb prompt all results looks Good.

Upvotes: 1

Views: 137

Answers (2)

Alex
Alex

Reputation: 3991

I think you are using Dropdown - Semantic UI React.you are getting a dropdown with no values because of the structure of your state. Dropdown options should be like this

 {
    key: "....",
    text: "...",
    value: "..."
  }

using map function to transform you row data to met Dropdown minimum requirements.
Update if MongoDB return a result

 rooms: [
        {
          _id: { $oid: "46746766474664" },
          RoomID: { $numberInt: "1" },
          RoomDesc: "1st Floor"
        },
        {
          _id: { $oid: "46746766474665" },
          RoomID: { $numberInt: "2" },
          RoomDesc: "2st Floor"
        }
      ]

then you can transform to desirable structure

  this.setState({
          options: [
            ...this.state.rooms.map(item => {
              return {
                key: item._id.$oid,
                text: item.RoomDesc,
                value: item.RoomID.$numberInt
              };
            })
          ]
        });

Working temporary Codesandbox sample with a dummy data.

Upvotes: 1

Sekru
Sekru

Reputation: 515

If rooms is array then you can't just use this.state.rooms.RoomID. Probably some loop or map needed

Upvotes: 0

Related Questions