Ivan Ludvig
Ivan Ludvig

Reputation: 103

Handling redux state with filtering, sorting and pagination done in backend

The user has access to a list of items and has the ability to search, sort and change pages. The API returns paginated, sorted and filtered items. When some parameters are changed, how should the new data merge with the current state? Just merging them together won't work because not all items should be shown when the user inputs a search query, for example.

My ideas:

Upvotes: 1

Views: 571

Answers (1)

HMR
HMR

Reputation: 39320

One way of doing this is storing each query, page is just another query argument:

{
  //the key is the query sent to the api
  //  this could be an url query string or
  //  the query object to json
  'page=1&sort-by=first&desc' : {
    //status of the request (explains itself)
    requested:true,
    loading:false,
    error:false,
    result:[2,1]//ids in this page
  },
  //here are all the data items with their own status
  data: {
    "1":{
      //request status (you may want to get)
      //  just one item by id
      requested:true,
      loading:false,
      error:false,
      //the actual entity
      result: {
        id: 1,
        first:'z'
      }
    },
    "2":{
      //loading, requested ...
      result: {
        id:2,
        first:"a"
      }
    }
  }
}

When you do crud then you should wipe out all the data from state because you are doing sorting and/or filtering on the server so any update could change any page set. You can add a status stale and refreshing so a component can show stale data but refresh it in the background. Normally you'd do caching in the service worker but since redux needs the status of your request you could add the extra effort and implement it in the (thunk) actions and selectors.

Upvotes: 1

Related Questions