6

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.

5
  • .filter and .sort are two different functions... you should use .sort even if you are using hooks Commented Jun 13, 2019 at 19:07
  • Wrong name.. for a prop and function i know. Commented Jun 13, 2019 at 19:08
  • it seems that It is not possible to filter this state please giva an example of how this isn't working. Commented Jun 13, 2019 at 19:09
  • For instance, I am getting map is undefined. Commented Jun 13, 2019 at 19:12
  • Anyway solved forgot to remove this because it will not work inside a stateless function. Commented Jun 13, 2019 at 19:16

1 Answer 1

13

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>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.