Tom Bom
Tom Bom

Reputation: 1721

How to pass an object to a reducer with state key

I'm building an app with React Native and I'm trying to record audio. I would like to pass an object to my action and then further to my reducer in order to update the state.

In my screen where I call the action:

this.props.recordAudio({ stoppedRecording: true, recording: false, paused: false });

Action:

export const recordAudio = (change) => {
  return {
    type: AUDIO,
    payload: change
  };
};

Reducer:

const INITIAL_STATE = {
  audio: {
    recording: false,
    paused: false,
    stoppedRecording: false,
  }
}

case AUDIO:
return {
  ...state,
  audio: {
    ...state.audio,
    [action.payload]
  }
}

I get an error: Unexpected token (Fatal). I also tried without brackets.

I have other keys inside audio and it's easier to update them all by directly passing key/value, instead of making a separate action for all of them. Is there a correct way to do this?

Upvotes: 1

Views: 1378

Answers (3)

Roozbeh Mohammadzadeh
Roozbeh Mohammadzadeh

Reputation: 689

case audio:
return {
      ...state,
  audio: {
      ...state.audio,
    [action.payload]
  }
}

Upvotes: 1

Isaac
Isaac

Reputation: 12874

You should remove the square bracket

case AUDIO:
return {
  ...state,
  audio: {
    ...state.audio,
    ...action.payload
  }
}

Upvotes: 0

Hậu Chử
Hậu Chử

Reputation: 80

You should spread Object action.payload like:

 case AUDIO:
        return {
          ...state,
          audio: {
            ...state.audio,
            ...action.payload
          }
        }

Upvotes: 1

Related Questions