Search code examples
reactjspromisexmlhttprequestreact-reduxreduce

Handling promises in the reduces using redux


I am building an web app using react + redux

I have a data table and the user is able to delete rows from the table

In order to avoid from the user to having to wait until the data is removed from the server (more accurately the database), I would like to go with the success oriented approach which means remove the item from the state and also send an HTTP request to delete this item from the database.

Both I would like to execute from the reducer

The question is where should I handle resolved or rejected promise? In case it was rejected I would also like to notify the user.

Thanks


Solution

  • where should I handle resolved or rejected promise? In case it was rejected I would also like to notify the user?

    It should be done in function that doing API call via reducers.

    //reducer

    const deleteRecord = (state="somestate")=>{
         fnAPICall()
    
    }
    
    function fnAPICall(){
        fetch('some_url').then(function(response) {
          if(response.ok) {
    
            dispatch({"type":"DELETE_RECORD",record_id : some_id});//actual delete from memory
    
             return response.json();
          }
    
          dispatch({"type":"DELETED_FAILED",record_id : some_id}); //Record deleting failed.notify user
        })
    }