user10408806
user10408806

Reputation:

How to filter array with Hooks?

I am currently working on a class-based function. Trying to convert the class to a stateless function, followed by refactoring my code for each event handler from this.SetState to useState (in this case setMovies).

This is my code (partial code):

const Movies = () => {
    const [movies, setMovies] = useState(getMovies());
    const [disabled, setDisabled] = useState(true);
    const [pageSize, setPageSize] = useState(4);

const sortBy = sortType => {
    setMovies(movies.filter(sortType));
    setDisabled(false);
    // this.setState({
    //     movies: this.state.movies.sort(sortType),
    //     isDisabled: false,
    // });
};

it seems that It is not possible to filter this state. I am able to change to boolean but can't filter my Array. Is there a way to filter using Hooks?

Thanks in advance.

Upvotes: 6

Views: 22343

Answers (1)

Dupocas
Dupocas

Reputation: 21317

Nothing changes...

const List = () => {
    const [items, setItems] = useState([1, 2, 3, 4, 5, 6])
    const filterEvenResults = () => setItems(items => items.filter(x => x % 2))
    return (
        <div>
            {
                items.map(item => <p key={item}>{item}</p>)
            }
            <button onClick={filterEvenResults}>Filter</button>
        </div>
    )
}

Upvotes: 13

Related Questions