Search code examples
javascriptreactjsfirebasefirebase-realtime-databaselodash

Adding conditions and sorting before rendering data


Wondering how I can only display something from my database to the screen only if it has a < 0 trend score, or > 0, etc.

In my render(), I have two instances using lodash:

const orderedPlayersUp = _.orderBy(players, ['votes'], ['desc']);
const orderedPlayersDown = _.orderBy(players, ['votes']);

These are working fine. In my database, people can up or down vote submissions and the left side (playersUp) shows the highest voted submissions and the right side is flipped and shows the lowest rated submissions at the top (trending down) Here's how the left side looks:

orderedPlayersUp.map((player) => {
            return (
              <Player
                playerContent={player.playerContent}
                playerId={player.id}
                key={player.id}
                upvotePlayer={this.upvotePlayer}
                downvotePlayer={this.downvotePlayer}
                userLogIn={this.userLogIn}
                userLogOut={this.userLogOut}
                uid={this.uid}
              />
            )

The problem is that both sides show ALL the submissions. For example, the left side correctly shows the highest voted submissions at the top, but as you scroll down, you'll eventually see those negative rated submissions (a submissions with -10 votes for example). I would like to have the orderedPlayersUp only show submissions with votes > 0, and the orderPlayersDown display submissions with votes < 0.


Here's the firebase layout (with the vote counts) and the way it displays to the screen. As you can see, if it was implemented how I want it to be, we'd only see John Doe and First Last in the trending up (cause they have 10 and 5 votes, respectively) and then Jane Doe and Test Name in the trending down, with -10 and -5 respectively.

enter image description here
enter image description here

Should I be using something other than lodash for this?


Solution

  • You could use JavaScript to filter unwanted values:

    const orderedPlayersUp = _.orderBy(players, ['votes'], ['desc']).filter(p => p.votes > 0);
    const orderedPlayersDown = _.orderBy(players, ['votes']).filter(p => p.votes < 0);