Emilis
Emilis

Reputation: 162

How to filter request to Firebase realtime database

i have this chat structure: Data structure

I now want to filer chats, so the user sees only chats where he is the member of the chat. As you can see every chat has members node, there is userId from firebase. How I can filter that in my request? Now I retrieve chats like this:

constructor(props) {
    super(props);
    this.state = { chats: [] };
    this.getChats = this.getChats.bind(this);
  }

  componentDidMount() {
    var _userId = firebase.auth().currentUser.uid;

    this.getChats(_userId);
  }

  getChats = _userId => {
    var readedData = firebase
      .database()
      .ref('chats')
      .orderByKey();
    readedData.once('value', snapshot => {
      this.setState({ chats: snapshot.val() });
      console.log(this.state.chats);
    });
  };

Thanks for the help! New structure: enter image description here

Upvotes: 0

Views: 120

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83181

The following should do the trick:

//....
var uid = 'NGIKTy2......';   //Set the member userId
var readedData = firebase
  .database()
  .ref('chats')
  .orderByChild('members/' + uid)
  .equalTo(true)
//....

Corresponding documentation: https://firebase.google.com/docs/database/web/lists-of-data#filtering_data

Upvotes: 1

Related Questions