neowenshun
neowenshun

Reputation: 960

How to append data to existing data object

Im currently using redux to manage my state. The scenario is as such , Upon successful creation of a new object , i would like to append the response data into my existing state container as i don't wish to make a new API call to render it.

initial State:

const initialState = {
workflowobject:{},

};

SAGA:

export function* workerCreateTransitionApproval(action) {
const data = yield call(() => axiosInstance.post(`/transition-approval-meta/create/`, action.data))
yield put({ type: "STORE_WORKFLOW_DATA", payload: data.data.data, fetch: 'workflowobject' , label: 'transition_approvals'})

}

So over here , i upon recieving the "signal" so to speak to create a transition approval , i will catch that event and create make an axios post request to my backend , which will then return a response of the transition_approval . I will then store this transition_approval as the payload which i will use later on.

Reducer

const loadWorkflowObject = (state, action) => {
    return updateObject(state, {
        workflowobject: { ...state.workflowobject, [action.label]: action.payload }
    })
}

const storeData = (state, action) => {
    switch (action.fetch) {
        case 'workflowobject': return loadWorkflowObject(state, action)
    }
}

const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'STORE_WORKFLOW_DATA': return storeData(state, action);
        case 'CLEAR_CLASS_STATES': return clearClassStates(state, action);
        case 'CLEAR_OBJECT_STATES': return clearObjectStates(state, action);
        default:
            return state;
    }
}

export default reducer;

So in my reducer , it will first go into the case STORE_WORKFLOW_DATA which will then return the reducer function loadWorkflowObject . This is where i wish to 'append' the data back to the state tree.

The problem

The tricky part here is that im using this loadWorkflowObject reducer for fetching data too , and im already using the spread operator here.

The code that i have shown above will override my preexisting data that i have in the transition_approvals object , if possible , i would like to append the data in instead.

Upvotes: 1

Views: 596

Answers (1)

Red Baron
Red Baron

Reputation: 7652

you can do this:

const loadWorkflowObject = (state, action) => {
    return updateObject(state, {
        workflowobject: { ...state.workflowobject, [action.label]: state. transition_approvals.concat(action.payload) }
    })
}

Upvotes: 1

Related Questions