Bomber
Bomber

Reputation: 10987

add object to initial state in reducer

I have my initial state:

export default function DrinkCalculator(state = initialState, action) {

  let payload = action.payload;
  switch (action.type) {
    case UPDATE_DRINKS_CALCULATOR:
    return [{
        ...state,
        ...payload
    }];
case ADD_DRINK:
  let newState= [Object.assign({},state)];
newState.push(action.payload);
return newState;

How can I add to my array to hold an array of objects? How would I need to change my reducer to add an object to an array, so I can store lots of entries rather than just one.

I would like my state to be:

[{
  drinkType: 5,
  drinkVolume: 4,
  drinkStrength: 5,
  drinkQuantity: 5,
  drinkStength: 5
},
{
  drinkType: 1,
  drinkVolume: 2,
  drinkStrength: 2,
  drinkQuantity: 5,
  drinkStength: 7
},
{
  drinkType: 3,
  drinkVolume: 5,
  drinkStrength: 2,
  drinkQuantity: 5,
  drinkStength: 5
},
{
  drinkType: 5,
  drinkVolume: 5,
  drinkStrength: 5,
  drinkQuantity: 5,
  drinkStength: 5
}
]

Update: I am getting nested objects copied into my state, I would like to get the top level properties and add them as an object to the array.

When I fire the action here:

onClick() {
const drinkQuantity = this.state.counter;

const drinks = this.props.DrinksCalculator;

if (!drinkQuantity) {
    this.props.dispatch(showError());
} else {
    this.props.dispatch(updateDrinksCalculator({drinkQuantity}));
// fire addDrink to copy drinks props in new object
    this.props.dispatch(addDrink( drinks ));

    this.props.router.push('/calc/5');
}
}

enter image description here

Upvotes: 1

Views: 3435

Answers (1)

Austin Poole
Austin Poole

Reputation: 785

If I understand you right you want to add an new attribute to your state.

const initialState = {
  drinkType: null,
  drinkVolume: null,
  drinkStrength: null,
  drinkQuantity: null,
  drinkStength: null
};
const someReducer=(state=initialState,action) => {
  switch (action.type) {
  case "SOME_ACTION":{
    let newState= Object.assign({},state,{newAttribute:["value1","value2"]});
    return newState;
  }
}

This creates a state that has the newAttribute property in it.

Personally I like listing all the properties I'm going to use in the initialState. It makes easier to to people reading your code what properties they are going to be using and the data within.

Another example of pushing an object into an array

dispatch({
  type:"ADD_QUESTIONS",
  question:{
    drinkType: 5,
    drinkVolume: 4,
    drinkStrength: 5,
    drinkQuantity: 5,
    drinkStength: 5
  }
})

const initialState = {
  questions:[]
};

const someReducer=(state=initialState,action) => {
  switch (action.type) {
  case "ADD_QUESTIONS":{
    let newState= Object.assign({},state);
    newState.questions.push(action.question);
    return newState;
  }
}

Upvotes: 1

Related Questions