reactjsreduxreact-reduxredux-actions

Call multiple actions jointly in React Redux


I am learning React Redux. My Action is like below

import Axios from 'axios';

export const getAddress = valueModal => dispatch => {
  return Axios.get('/api/address')
    .then(response => {
      var addressData = response.data;
      dispatch({
        type: 'getAddresses',
        payload: { addressData, valueModal }
      });
    })
    .catch(function(error) {
      console.log(error);
    });
};

export const uploadImage = (formData, id, config) => dispatch => {
  return Axios.post('/api/address/upload', formData, config)
    .then(response => {
      dispatch({
        type: 'uploadImage',
        payload: response.data
      });
    })
    .catch(function(error) {
      console.log(error);
    });
};

export default { getAddress, addAddress, uploadImage };

My Reducer is like below

const initialState = {
    address: {}
};

const addressReducer = (state = initialState, action) => {
    switch (action.type) {
        case 'getAddresses': {
            return {
              controlModal: action.payload.valueModal,
              address: action.payload.addressData
            };
        }
        case 'uploadImage': {
            return {
                uploadImage: action.payload
            };
        }
        default:
            return state;
    }
};

export default addressReducer;

I would like to call getAddresses and uploadImage jointly. How can I do that ?

enter image description here


Solution

  • const initialState = {
        address: {}
    };
    
    const addressReducer = (state = initialState, action) => {
        switch (action.type) {
            case 'getAddresses': {
                return {
                  ...state,
                  controlModal: action.payload.valueModal,
                  address: action.payload.addressData
                };
            }
            case 'uploadImage': {
                return {
                    ...state,
                    uploadImage: action.payload
                };
            }
            default:
                return state;
        }
    };
    
    export default addressReducer;
    

    You need to spread the object state out otherwise there is never a reference to the state before the update.

    The object spread syntax lets you use the spread ... operator to copy enumerable properties from one object to another in a more succinct way.