1

Let's say there's child component fetching and rendering posts...

const Child = () => {
    const {data} = useGetPostsQuery({
        start: moment().subtract(1, 'months'),
        end: moment()
    })    

    return (
    //...
        {data.map
        //...       
        }
    )

}

And there's Parent component which does render Child component and DatePicker component.

const Parent = () => {
    const [filters, setFilters] = useState({start: '', end: ''});
    const {} = useGetPostsQuery({
        start: filters.start,
        end: filters.end
    })     
    // handles when user click search button
    const onSearch = (e) => {
       setFilters(//...)
    }
    
    return (
    //...
        <DatePicker name="start" />
        <DatePicker name="end" />
        <Child />
    //...
    )
}

At first, I thought changing argument from other components will affect cached data and re-render Child component again. Unfortunately It doesn't.

RTK Query, apparently, uses argument as a key for query endpoint therefore each hooks in Parent/Child components have different keys.

I'm just wondering what is the bes way to handle this problem. The first idea I was thinking of is making filters as global state using redux like this...

const Parent = () => {
    //...    
    // handles when user click search button
    const onSearch = (e) => {
       dispatch(setFilters(//...));
    }
//...


const Child = () => {
    const {postFilters} = useSelector(//...);
    const {data} = useGetPostsQuery({
        start: postFilters.start,
        end: postFilters.end
    })
    //...  

Please let me know if there's better way than this. (Excuse my ignorance, I always use saga/thunk for data fetching and this is my first time trying RTK Query.)

loone96
  • 723
  • 2
  • 13
  • 21

0 Answers0