0

Hello I'm looking to filter my state in my reducer. to display them in a Flatlist.

unfortunately my state is filtered only once.

what's wrong with the reducers.🤔

here is a youtube video https://www.youtube.com/watch?v=u1Y2PtLk-ck

const initialState = {
  data: ''
}

export default (state = initialState, { type, payload }) => {
  switch (type) {
    case 'FETCH_DATA':
      return { ...state, data: payload }
    case 'ORDER':

      return {
        ...state,
        data: state.data.filter(user => user.dob.age >= payload.minAge && user.dob.age <= payload.maxAge)
          .map(user => user)
      }
    default:
      return state
  }
}

1 Answer 1

1

Order action #1:

state.data = previous state.data, filtered to only include older people

Order action #2:

state.data = previous state.data (previously filtered to only include older people), filtered again to only include older people and younger people. Results are the same, because only older people (from previous result) are in this dataset now.

Redux: what is the correct way to filter a data array in reducer?

https://redux.js.org/recipes/computing-derived-data

tl;dr

  1. Try to keep computed properties (like filtered data) in mapStateToProps functions, not in the reducer
  2. If these mapStateToProps functions are reused, might want to look into selectors/reselect library
  3. If you're adamant about storing the filtered data in the reducer, use a separate property like filteredData instead of data, so it is not overwritten

Also, you can remove the .map() after .filter() as it is not doing anything (only returning the same elements that are already there).

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.