0

For practice with Redux, I have in index.js

const state = [
  {
    resort: 'Jay Peak',
    date: '2018-2-22',
    powder: true,
    backcountry: false,
  },
];

const action = {
  type: constants.ADD_DAY,
  payload: {
    resort: 'Mad River Glen',
    date: '2018-3-14',
    powder: true,
    backcountry: false,
  },
};

const nextState = allSkiDays(state, action);

console.log(`

  initial state: ${JSON.stringify(state)}
  action: ${JSON.stringify(action)}
  new state: ${JSON.stringify(nextState)}

  `);

and my reducers for composition,

export const skiDay = (state = [], action) => {
  action.type === constants.ADD_DAY ? action.payload : state;
};

export const allSkiDays = (state = [], action) => {
  switch (action.type) {
    case constants.ADD_DAY:
      return [...state, skiDay(null, action)]; // COMPOSITION!!!! use skiDay()
    default:
      return state;
  }
};

and I keep getting this result,

  initial state: [{"resort":"Jay Peak","date":"2018-2-22","powder":true,"backcountry":false}]
  action: {"type":"ADD_DAY","payload":{"resort":"Mad River Glen","date":"2018-3-14","powder":true,"backcountry":false}}
  new state: [{"resort":"Jay Peak","date":"2018-2-22","powder":true,"backcountry":false},null]

I've tried many things why is null still being spread onto the array and not the new object?

1
  • 1
    You might want to put a return before action.type, or remove the curly brackets in the function skiDay. Commented Aug 8, 2018 at 18:05

1 Answer 1

1

This reducer is not returning the next state.

export const skiDay = (state = [], action) => {
  action.type === constants.ADD_DAY ? action.payload : state;
};

Do this instead:

export const skiDay = (state = [], action) => {
  return action.type === constants.ADD_DAY ? action.payload : state;
};
Sign up to request clarification or add additional context in comments.

1 Comment

I thought that in this case the arrow function implicitly returns. I realize it was the curly braces the called for the return keyword. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.