Matias Thompson
Matias Thompson

Reputation: 57

state destructuring trouble in redux

SUMMARY

I'm rewrite the redux state, destructuring subtree, but part of state is missing after that

PROJECT INFO

Dependencies on my react project:

CODE

initial state:

const initialState = {
  fetching: false,
  data: {
    events: null,
    issues: null,
    sla: {
      daily: null,
      weekly: null,
    },
    lastUpdate: null,
  },
  error: null,
};

part of reducer where missing data:

case types.FETCH_DATA.SUCCESS:
  return {
    ...state,
    data: {
      ...state.data,
      sla: {
        ...state.data.sla,
        ...payload.data.sla,
      },
      ...payload.data,
    },
    fetching: false,
    error: null,
  };

data send by action:

{
  events: ["event 1", "event 2"],
  issues: ["issue 1", "issue 2"],
  sla: {
    daily: ["daily 1", "daily 2"],
}

state after action dispatch:

{
  fetching: false,
  data: {
    events: ["event 1", "event 2"],
    issues: ["issue 1", "issue 2"],
    sla: {
      daily: ["daily 1", "daily 2"],
    },
    lastUpdate: null,
  },
  error: null,
}

data.sla.weekly is missing

if i don't send issues on action:

{
  events: ["event 1", "event 2"],
  sla: {
    daily: ["daily 1", "daily 2"],
}

state after action dispatch:

{
  fetching: false,
  data: {
    events: ["event 1", "event 2"],
    issues: null,
    sla: {
      daily: ["daily 1", "daily 2"],
    },
    lastUpdate: null,
  },
  error: null,
}

In this case ...state.data destructuring is working well, but ...state.data.sla not

please, someone to help me!!!

Upvotes: 0

Views: 968

Answers (1)

Ewe Tek Min
Ewe Tek Min

Reputation: 865

The destructuring is working as expected but your sequence should change

case types.FETCH_DATA.SUCCESS:
  return {
    ...state,
    data: {
      ...state.data,
      sla: {
        ...state.data.sla,
        ...payload.data.sla,
      },
      ...payload.data, <---- This is overriding the previous `sla` but the action contains `sla.daily` only, that's why your `sla.weekly` is gone
    },
    fetching: false,
    error: null,
  };

Try to change a sequence

case types.FETCH_DATA.SUCCESS:
  return {
    ...state,
    data: {
      ...state.data,
      ...payload.data, <-- Move up before `sla`
      sla: {
        ...state.data.sla,
        ...payload.data.sla,
      },
    },
    fetching: false,
    error: null,
  };

But your state seems like quite complicated, if possible, simplify it would make your life easier...

Upvotes: 1

Related Questions