Hakutsuru
Hakutsuru

Reputation: 73

Which is better CRUD coding style using Redux?

I have a simple question about coding style for single page application. My front end is using React Redux

For example I have a standard CRUD page where data is displayed in table and pop up modal form. Data table is filtered from the server not from the client.

My question : If i create, update or remove a data should I call a refresh function or just edit it in redux store?

Refresh function :

  1. Data always updated
  2. Newly added data is filtered
  3. Two times request, slower, unresponsive (Main problem)

Redux store:

  1. App looks responsive
  2. One time request
  3. Lost server side filter function and data is not updated if multiple users is using the app (Main Problem)

Any advice will be appreciated

Upvotes: 1

Views: 413

Answers (3)

Lyubomir
Lyubomir

Reputation: 20037

Dispatch an async action which queries the server where filter happens and when it resolves, update redux state with the refreshed, filtered data.

Pseudocode

// dispatches an action to refresh data without page reload
export function refreshDataAction() {
  return (dispatch, getState) => {

    return (
      fetch('api/data', options) // fetch the data from server and let it filter
      .then(data => dispatch(updateDataAction(data)))
    );
  };
}

// dispatches an action to update redux state with filtered data
export default function updateDataAction(data) {
   return { 
     type: 'UPDATE_DATA',
     ...data,
   }
}

Then you could just call dispatch(refreshDataAction()). Data is filtered, no page refresh.

Upvotes: 0

jankoritak
jankoritak

Reputation: 595

Calling refresh in a React application (not only React, but any real-time front-end app) kind of defies whole principal of using React.

What you should do is, whenever there occurs a data-changing operation in your client, you should trigger an API call, that alters your server-side data accordingly. Send the data back to the client (you can send it to all clients, if you fancy web-socket), save it to the Redux state to trigger a re-render.

Upvotes: 0

alebianco
alebianco

Reputation: 2555

Edit the store locally to give immediate feedback, then send the request and when you get the reply back consolidate the store with the new data

basically, do both things and get the best benefit of both worlds

Upvotes: 1

Related Questions