Search code examples
reactjsreduxredux-offline

How to add an action to dispatch instead of the url in effect when using redux-offline


I am using "redux-offline" to make my application work offline. I want to dispatch an action in the effect part and get the back end result to the commit part.

meta: {
        offline: {
                effect: { type: "CHECK_NUMBER"  },
                commit: { type: "DISPLAY_NUMBER" },
                rollback: { type: TYPES.CHECK_NUMBER, meta: { data } }
            }
        }

I want to fire the "CHECK_NUMBER" at the first place and get the result back to the commit part.


Solution

  • I found out that an action can't be fired in "meta.offline.effect". We can add an action to be fired in "meta.offline.commit" and "meta.offline.rollback". I used "redux-saga" to send calls to the API and get back the results and now my application is working in offline mode.

        ex: export const addCustomer = (data) => {
            return {
                type: TYPES.ADD_CUSTOMER,
                payload: { data },
                meta: {
                    offline: {
                        effect: { },
                        commit: { type: "SUBMIT_CUSTOMER", meta: { data } },
                        rollback: { type: TYPES.SUBMIT_CUSTOMER, meta: { data } }
                    }
                }
            }
        }
    

    In saga :

    function* submitCustomer(action) {
    
        const data = { FirstName: action.meta.data };
        const result = yield axios.post(`https://localhost:44300/api/Values/SubmitCustomer`, data)
        .then(Response => Response).catch(error => {
            throw error
        });
    }
    
    function* customerSaga() {
        yield takeEvery("SUBMIT_CUSTOMER", submitCustomer);
    }
    
    export default customerSaga;