Search code examples
reactjsreact-reduxredux-toolkitrtk-query

How to access RTK query data in another slice?


I'm currently making an e-commerce application as a practice project. I use an API slice to fetch product data and then display it in the front-end with the auto-generated hook. I want to implement some filters that the user can use to view products that match them, like price, colors, etc. The problem I have is that I'm not sure how to access the data from a filters slice.

I want a button that clears all filters so modifying and deleting the data from the API slice doesn't seem like the correct approach, and it would require additional re-fetchs if the user changes the filters. Having a different slice for filters seems like the correct approach but I'm not sure how to handle this .If simply copy the data into the filters slice there's a risk of it being outdated or de synchronized, and there would have to be more functionality to ensure the copied data is always correct. Ideally the filter slice would be "connected" to the API slice data.

What would be the best way to implement this?


Solution

  • Instead of trying to filter and store the queried data let the API slice cache the fetched/requested data, and create a filters state slice that stores the filtering criteria, then use the query hook and a selector function to select the filter state to compute the derived filtered data to render.

    const { data } = useQuery();
    const filters = useSelector(filtersSelector);
    
    const filteredData = useMemo(() => {
      // apply filtering logic and return computed filtered data
    }, [data, filters]);
    
    ...
    
    // render UI with computed filteredData
    

    From the filtering UI you'll dispatch actions to the filter state slice to set/toggle/etc the filtering criteria, including any state to indicate "no filtering" to display the complete fetched/cached data.