Add a selector using reselect in redux

Viewed 466

I created an application what filters data according to user input.

// ui component
import React from 'react';
import { useDispatch, useSelector } from "react-redux";
import { searchPersonAction } from "../store/actions/search";

const Search = () => {
    const dispatch = useDispatch();
    const selector = useSelector(s => s.search);
    const search = (e) => {
        const txt = e.target.value;
        dispatch(searchPersonAction(txt));
    };
    return (
        <div>
            <input onChange={search} placeholder="search"/>
            <ul>
                {
                    selector.name.map(p => <li key={p.name}>{p.name}</li>)
                }
            </ul>
        </div>
    );
};

export default Search;

// action
import { SEARCH } from './actionTypes';
import { persons } from "../../mock__data";

export const searchPersonAction = (person) => {
    const personSearched = persons.filter(p => p.name.toLowerCase().includes(person.toLowerCase()));
    console.log(personSearched);
    return {
        type: SEARCH.SEARCH_PERSON,
        payload: personSearched,
    }
};


//reducer

import { SEARCH } from '../actions/actionTypes';
import { persons } from "../../mock__data";

const initialState = {
    name:persons
};

export const search = (state = initialState, { type, payload }) => {
    switch (type) {
        case SEARCH.SEARCH_PERSON:
            return {
                ...state,
               name: payload
            };
        default:
            return state;
    }
};

Above I filter using: const personSearched = persons.filter(p => p.name.toLowerCase().includes(person.toLowerCase())); and I get on ui using above Search component.
Question: How to use reselect library in my example?

1 Answers

The examples in the Reselect documentation will get you there. The filtering you mentioned would become your reselector:

import { createSelector } from 'reselect'
import { persons } from "../../mock__data";

const nameSelector = state => state.name;

export const searchedPersonsSelector = createSelector(
  nameSelector,
  name => persons.filter(p => p.name.toLowerCase().includes(name.toLowerCase()));
);

inside your component you can import the selector and use the useSelector hook as you are already doing:

import { searchedPersonsSelector } from "./selectors";

const Persons = () => {
  const searchedPersons = useSelector(searchedPersonsSelector);
  return (
    ...
  );
};

Related