ReactJS useReducer filter functions directly in the state

Viewed 723

I'm looking into React Hooks and I encountered a question while using React Reducer.

Is it a good way to directly define filter functions in the state for the respective state? Or does it destroy the mental programming model?

import ...

export const ExpensesContext = createContext([]);

const initialState = {
    Expenses: [],
    // 
    GetExpensesFromCategory(category: string) {
        return this.Expenses.filter(i => i.Category === category)
    }
};

function reducer(state, action) {
    switch (action.type) {
        case "update":
            return {...state, ...action.payload};
        case "delete":
            return {};
    }

    return state;
}

const ExpensesStore = ({children}) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    const [userState] = useContext(UserContext);

    useEffect(() => {
        // some behaviour
    }, [userState]);

    return (
        <ExpensesContext.Provider value={[state, dispatch]}>
            {children}
        </ExpensesContext.Provider>
    )
};

export default ExpensesStore;
0 Answers
Related