Home > Software engineering >  How to replace redux like store with react-query cache efficiently?
How to replace redux like store with react-query cache efficiently?

Time:02-26

I am fetching a list of movies using useQuery and previously i was using a redux to store these movies and i had a search functionality where when i search i look for the movies in the store. Now i am trying to replace this with cached results of the queries of the movies using react-query:

    const queryClient=useQueryClient();
    let queryClientPopular=queryClient.getQueryData('Popular')?.data?.results;
    let queryClientUpcoming=queryClient.getQueryData('Upcoming')?.data?.results;
    let queryClientTopRated=queryClient.getQueryData('Top Rated')?.data?.results;
    
    const getMovieIdForPlaceholderData=(queryClientMovies,query)=>{
        return queryClientMovies?.filter(movie=>movie.original_title.toLowerCase().startsWith(query));
     }
     
     const filterMovies=(query)=>{
        let dataQuery;
        let queryClientArr=[queryClientPopular,queryClientTopRated,queryClientUpcoming];
            
        for(let i=0;i<3;i  ){
            dataQuery=getMovieIdForPlaceholderData(queryClientArr[i],query)
            if(dataQuery)break;
        }
    
        
        //let arr=globalState?.movie?.filter(mov=> {return mov.original_title.toLowerCase().startsWith(query)});
        //console.log(arr);
        setFilteredMovies(dataQuery);       
    }

I have two concerns:

  1. The code looks very hacky and messy to me

  2. if the user refreshes i lose the query cache data For this issue, I thought about using useQuery to fetch the movies again just so i can search them. But it seems very inefficient.

Is there a better way to fix these issue? Or should I just stick to my Redux store for this?

CodePudding user response:

React Query is meant to cache server responses, not have you "search within those" locally. The underlying logic here is that at some point the server will hold so much data that you cannot pass all of it to the client to search it there anyways - so you should just make a request to the server for everything.

This works fine in most cases and even in Redux Toolkit, we have a similar approach with RTK Query.

If you find yourself manually fiddling around with results to create something new, it might just not be the right tool for you though. Those "Query" libraries are document caches, not normalized caches. They are excellent for "mirroring the server", but not meant for "locally massaging the data". If you want to do the latter, you probably have to keep manually managing your state.

  • Related