Manav Pandya
Manav Pandya

Reputation: 89

How to add new object into existing state using react and redux saga

I have an object with information like this.

export const initialSettings = {
  id: '01',
  name: '',
  lat: '',
  long: '',
  adressLine1: '',
  adressLine2: '',
  city: '',
  state: '',
  country: '',
  zipcode: '',
  status: '',
  lastCommunicateDateTime: '',
    {
      PatientID: '1',
      FirstName: 'Manav',
      LastName: 'Pandya',
      DateOfBirth: '',
      MobileNo: '',
      orders: [
        {
          orderId: '01',
          pickupCode: 'XYZ456',
          totalAmount: 40.0,
          taxPercentage: 3,
          insuranceAmount: 20.0,
          totalCoPayAmount: 40.0,
          totalPaidAmount: 40.0,
          totalDueAmount: '',
          paymentDueDate: '',
          items: [
            {
              itemId: '01',
              image: 'https://via.placeholder.com/30',
            }
          ]
        }
      ]
    },
    {
      PatientID: '2',
      FirstName: 'Manav',
      LastName: 'Pandya',
      DateOfBirth: '',
      MobileNo: '',
      orders: [
        {
          orderId: '01',
          pickupCode: 'XYZ456',
          totalAmount: 40.0,
          taxPercentage: 3,
          insuranceAmount: 20.0,
          totalCoPayAmount: 40.0,
          totalPaidAmount: 40.0,
          totalDueAmount: '',
          paymentDueDate: '',
          items: [
            {
              itemId: '01',
              image: 'https://via.placeholder.com/30',
            }
          ]
        }
      ]
    }
  ]
};

But when I'm trying to add a new item using a reducer, then the old state was removed and won't get the proper state

Whenever I post my form with the different details than previous objects are removed and the new object added inappropriately

My reducer for the request looks like this.

 case 'add':
      return Map({
        state: {
          ...state, // old object should remains same
          patients: [state.patients, action.payload] // new item
        }
      });

Upvotes: 0

Views: 1454

Answers (2)

Alican Çelik
Alican Çelik

Reputation: 63

You should add reducer ;

case 'add':
  return {
    ...state,
    error: false,
    loading: false,
    data: state.data.concat(action.data), }

after that you need selector to send your data from selector to state ;

export const getDataDetail = state => getDataDetail(state)?.data;

last option is you should call your updated data . You should use

componentWillRecieve(nextProps) {
  ...... use your data match with nextProps and props
 if(nextData && nextData !== this.props.yourData) {
     this.setState({ data : nextData }) }}

it should be like that .

Upvotes: 0

Binesh Chaurasiya
Binesh Chaurasiya

Reputation: 36

It should be like this in reducer:

case 'add':
    return {
        ...state, // old object should remains same
        patients: [state.patients, action.payload] // new item
    };

Upvotes: 1

Related Questions