user10408806
user10408806

Reputation:

how to sort "toggle" data on click?

I'm wondering if is it possible to toggle/onClick data and sort it for instance from A to Z & Z to A but without creating multiple methods.

I have some sorting functions but I want this to be a toggle.

Of course I can create another function and do this.. but I'm would like to know if I can do it a cleaner way.

i have:

sortByTitle = () => {
    this.sortBy((a, b) => a.title.localeCompare(b.title));
    console.log('Sorted by title.');
};

But how can i revert back to sort from B to A without having to create another function?

My code:

import React, { Component } from 'react';

import { getMovies } from '../../services/fakeMovieService';

import TableHeader from './TableHeader';
import TableBody from './TableBody';

class Movies extends Component {
    state = {
        isSorted: false,
        movies: getMovies(),
        isDisabled: true,
    };

    sortBy = sortType => {
        this.setState({
            movies: this.state.movies.sort(sortType),
            isDisabled: false,
        });
    };

    // Display all movies but not the one selected.
    handleDelete = movie => {
        this.setState({
            movies: this.state.movies.filter(m => m._id !== movie._id),
            isDisabled: false,
        });

        console.log(`Movie ${movie.title} deleted.`);
    };

    // Sort by title.
    sortByTitle = () => {
        this.sortBy((a, b) => a.title.localeCompare(b.title));
        console.log('Sorted by title.');
    };

    // Sort by genre.
    sortByGenre = () => {
        this.sortBy((a, b) => a.genre.name.localeCompare(b.genre.name));
        console.log('Sorted by genre.');
    };

    // Sort by stock size.
    sortByStock = () => {
        this.sortBy((a, b) => a.numberInStock - b.numberInStock);
        console.log('Sorted by stock size.');
    };

    // Sort by rating score.
    sortByRating = () => {
        this.sortBy((a, b) => a.dailyRentalRate - b.dailyRentalRate);
        console.log('Sorted by rating.');
    };

    // Add class to the reset button based on the current filter state.
    resetButtonClass = () => {
        let btnClass = 'btn btn-sm btn-';
        btnClass += this.state.isDisabled ? 'warning' : 'primary';
        return btnClass;
    };

    // Reset sorted data.
    resetFilter = () => {
        this.setState({
            movies: [...getMovies()],
            isDisabled: true,
        });

        console.log('Reset sorted movies data.');
    };

    render() {
        const { length: count } = this.state.movies;

        // Check if there are movies available.
        if (count === 0)
            return (
                <React.Fragment>
                    <h4>There are no movies in the database.</h4>
                    <button
                        type="button"
                        onClick={this.resetFilter}
                        className="btn btn-primary btn-sm">
                        Reset
                    </button>
                </React.Fragment>
            );

        return (
            <React.Fragment>
                <h5>Showing {count} in the database.</h5>
                <table className="table table-hover table-striped table-dark">
                    <TableHeader
                        sortByTitle={this.sortByTitle}
                        sortByGenre={this.sortByGenre}
                        sortByStock={this.sortByStock}
                        sortByRating={this.sortByRating}
                        resetFilter={this.resetFilter}
                        resetButtonClass={this.resetButtonClass()}
                        isDisabled={this.state.isDisabled}
                    />

                    <TableBody
                        movies={this.state.movies}
                        handleDelete={this.handleDelete}
                    />
                </table>
            </React.Fragment>
        );
    }
}

export default Movies;

Upvotes: 0

Views: 648

Answers (1)

ThatCoderGuy
ThatCoderGuy

Reputation: 677

In javascript you can use sort() to sort the values of an array in alphabetical order (A-Z), if you then invoke the reverse() method you can then order descending (Z-A)

So in pseudocode you could have a function called sortData which accepts a true/false value to order inReverse (defaulting to false)

In your state you can have a value which tracks the current order

this.state{
    data:['Banana','Pineapple','Apple','Raspberry'],
    reverseOrder:false
}

sortData(reverseOrder = false)
{
    let sortedData = this.data.sort();

    if(reverseOrder)
       sortedData.reverse();
    this.setState(reverseOrder: !this.state.reverseOrder, data:sortedData)
}

Upvotes: 1

Related Questions