Learn

In the previous exercise, we wrote reducers that returned a new copy of the state rather than editing it directly. We did this to adhere to the rules of reducers provided by the Redux documentation:

  1. They should only calculate the new state value based on the state and action arguments.
  2. They are not allowed to modify the existing state. Instead, they must copy the existing state and make changes to the copied values.
  3. They must not do any asynchronous logic or have other “side effects”.

By asynchronous logic or “side effects”, we mean anything that the function does aside from returning a value, e.g. logging to the console, saving a file, setting a timer, making an HTTP request, generating random numbers.

These rules make Redux code predictable and easy to debug: tests run reliably and other developers know what to expect from your code.

Instructions

1.

We have some reducers here that are breaking the rules!

The reducer in app1.js violates the first rule of reducers: it calculates the new state based on something other than the current state and action arguments.

Fix this by assuming that the song being added will be passed into the reducer as the payload of the action object.

2.

The reducer in app2.js violates the second rule of reducers: it modifies the existing state.

Fix this by using the spread operator ... within a new array instead of using push() on the existing state.

3.

The reducer in app3.js violates the third rule of reducers: it has a side effect. The initial state will not be the same every time you call the reducer.

Fix this by assuming that the random value will be provided as the payload of the action object.

Note that this reducer is called with undefined. In this case, the default parameter will be used to set state.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?