02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Creating Multiple Counters with Redux and Arrays

Creating Multiple Counters with Redux and Arrays

In this tutorial, we'll walk through the process of creating multiple operational counters using Redux and arrays in React. This builds upon our understanding of managing state effectively and ensuring immutability through the use of tools like Object.freeze.

Introduction

To build dynamic and scalable applications, it's important to understand how to manage multiple instances of a component—such as counters—using Redux. In this lecture, we'll extend our previous example of a single counter and make our application capable of handling multiple counters. The key concepts we'll cover include:

  • Connecting our array of counters to components
  • Ensuring immutability of the state using ES6 tools
  • Handling multiple counters through Redux

Step 1: Managing State with Arrays

We start by storing multiple counters in an array. Redux helps us maintain the state for all counters centrally, making it easier to synchronize state across components. By converting our single counter to an array, we can now handle multiple counters more efficiently.

Updating State with Arrays

To create multiple counters, we change the way our state is managed by updating the reducer to work with arrays. Instead of handling a single value, the state will now be an array where each element represents a separate counter.

To make sure that we never modify our state directly, we use the ES6 spread operator. This ensures that any updates to the counters create new instances of the state, which is essential for preserving immutability.

const countersReducer = (state = [0, 0, 0], action) => {
  switch (action.type) {
    case 'INCREMENT':
      return [
        ...state.slice(0, action.index),
        state[action.index] + 1,
        ...state.slice(action.index + 1)
      ];
    case 'DECREMENT':
      return [
        ...state.slice(0, action.index),
        state[action.index] - 1,
        ...state.slice(action.index + 1)
      ];
    default:
      return state;
  }
};

In this example, INCREMENT and DECREMENT actions are handled by creating new arrays based on the previous state, incrementing or decrementing the relevant counter while keeping the rest intact.

Step 2: Connecting Redux State to Components

Next, we connect the Redux state to our React components so that each counter can receive its own value from the Redux store. We do this by using the mapStateToProps function to pass the array elements to individual counter components.

const mapStateToProps = (state, ownProps) => {
  return {
    count: state[ownProps.index]
  };
};

Here, each counter component will receive a specific value from the state based on its index. This enables us to render a list of counters, each being updated independently.

Step 3: Adding Actions to Modify Counters

To modify the counters, we dispatch actions from the components. Each action specifies the index of the counter that needs to be modified, ensuring that only the intended counter is updated.

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onIncrement: () => dispatch({ type: 'INCREMENT', index: ownProps.index }),
    onDecrement: () => dispatch({ type: 'DECREMENT', index: ownProps.index })
  };
};

This setup ensures that each counter component can independently increment or decrement its value while still using the same Redux store for the overall state management.

Step 4: Ensuring Immutability with Object.freeze

A critical aspect of working with Redux is ensuring that we do not modify the state directly. This is where Object.freeze comes into play, particularly in a development environment. By using Object.freeze, we can catch mutations and make sure that all updates happen in a controlled and predictable way.

const initialState = Object.freeze([0, 0, 0]);

Using Object.freeze helps us ensure that the state remains immutable and that we are adhering to best practices when working with Redux.

Summary

In this tutorial, we:

  1. Learned how to manage multiple counters using Redux and arrays.
  2. Connected the state from Redux to individual React components.
  3. Made sure our counters were updated in an immutable way using the ES6 spread operator and Object.freeze.

This approach is essential for keeping our state predictable, making it easier to debug and reason about. With Redux, handling multiple instances of the same component becomes much simpler and more efficient, allowing us to scale our applications effectively.

Video Transcript

00:01All right, so it's time for us to address the elephant in
00:03the room that was introduced in the last lecture
00:05and that is DU reduction.
00:07How does it deal with complex data types
00:09and generally speaking, how you wanna really address gen,
00:12uh, complex data types.
00:14And we're gonna start it off with a raise in this lecture,
00:16but really think about it as well about objects in general.
00:19Hint with the help of object freeze, which will really,
00:22really help you think about it.
00:23So then this lecture we'll introduce object freeze
00:25as our way to test to make sure that we're not
00:28actually modifying our state directly.
00:30Alright, so to approach, so we decided
00:33that we have three calendars.
00:34Okay? So that's good. Now the next step obviously if we have
00:38three counters is to make sure that our application itself,
00:42that now is getting an array
00:43and not an actual uh,
00:45string will actually send the right
00:47properties to the right place.
00:49So that's easy enough. I'm just gonna go ahead
00:51and add here our array indexes into our counters.
00:54Go ahead and save it. Okay, so that's really all we have
00:57to change in our visual layer at this stage to present
01:00and show our initial state of our counters.
01:04But the next step that we wanna do, the next step
01:07that we wanna approach
01:08and oh, we also wanna make sure
01:10that when we send our data, that's data.
01:13No, we're good. Okay.
01:15So the next step that we wanna do in our approach
01:17as we're building out our data is
01:20to go into our store itself
01:21and make sure that we're not actually physically changing
01:24anything directly, but we're gonna have a small problem.
01:28For one is we won't, we don't know what state,
01:31what element in of RA do we wanna change.
01:34Now to address that problem,
01:36we're gonna go back into our components themselves.
01:39And what I want to do is I'm gonna go into my app itself
01:41for now and I'm gonna add here oto an index.
01:45And for now let just hard code that index
01:47to be a value which will correlate to the value of our ra.
01:50And don't worry, as we progress in our course,
01:53we're gonna make our code a lot more,
01:55um, accurately defined.
01:57So we're not gonna be, um,
01:59we're not gonna doing wrong things,
02:00although you might find some things here wrong
02:02'cause there are a lot of these lock-ins of data inside
02:05of our visual layer is probably not what we wanna do
02:08'cause we're lacking in the exact data structure into our
02:12visual layers, which is something
02:13that we wanna reduce as much as we can.
02:15But for now we're not gonna reduce it.
02:17We're just gonna accept that as part of our reality inside
02:20of our counters themselves.
02:21I'm gonna go ahead in our dispatch man.
02:23I'm going to also want to send in that index
02:26that we've just added into our counters.
02:28So I'm literally just gonna go ahead here
02:30and fetch our index and it's gonna come from our props.
02:35And let me just go ahead and duplicate that twice
02:39and make sure that I'm sending in that index down
02:42as I'm making this dispatch.
02:45Beautiful. And we have our index. Beautiful.
02:49So now that we have an index, we know what we want
02:51to change, our counter is gonna announce to the at
02:54to the store within the action itself.
02:57Not only the action itself as it was so far,
03:00but now we're gonna have our type as we did before,
03:04but we're also gonna have our index.
03:06And now that we have our type N index,
03:08I'm just gonna go ahead here and make the modification
03:10'cause I'm basically de destructuring our object on the fly.
03:14What I'm gonna do is instead of doing, first of all,
03:16I'm gonna delete this push
03:17because one, we said we never wanna push stuff,
03:19we never want to physically make a change to our object.
03:23And in this case, what, what do we wanna do?
03:25We want to change the counter of the specific index.
03:29So we will not go and approach that index directly.
03:32We're not gonna go to state index
03:33and just modify it
03:35by adding one, Right?
03:39That would be a no. So we're not gonna do that.
03:42That is a no.
03:44Instead of that, what we're gonna do is we're gonna create a
03:46new array and we're gonna use e es six uh, logic here again.
03:51So I'm going to put here a dot,
03:53dot dot which is the spread attribute which will enable me
03:56to basically put in a first ch chunk of our array,
04:00which in this case we want everything that is
04:02before our index.
04:03So to do that I'm gonna go to my state
04:05and request to get a slice out of it, we want
04:08to get our slice to be from zero through our index.
04:12The next item is actually gonna be our state plus,
04:15but instead of doing plus plus,
04:17I'm literally just gonna assign the actual value itself
04:19there and it's gonna be plus one.
04:26Ugh, I hate that they're not aligned here, right?
04:28Don't you as well, eh, whatever.
04:31No, I, I I got it, I got it. I gotta study it.
04:33It's just driving me crazy. Okay.
04:35And the last property isso, we wanna take this,
04:37we wanna slice again,
04:39but this time around we just need our index there
04:42because we wanna, we're not gonna start from zero,
04:44we're actually gonna start from our index plus one.
04:46So we don't have a duplicate of that index.
04:48So what we're literally doing is we're getting a copy
04:52from a, our RA of the initial place we're getting,
04:54we're adding in the value that we want to change.
04:58And last but not least, we're also slicing out everything
05:01that is after that stage.
05:02And that's what we're gonna be sending back.
05:04The same applies by the way out.
05:06And this should be a dot, dot.as well.
05:08'cause we wanna have your spread.
05:09We don't want to actually put your NRA, we want
05:12split out all the content that's from within it.
05:15Last but not least, let's go ahead
05:17and implement this oso for our step down.
05:19So for our step down, literally the only difference is,
05:22is in our step down, we're gonna go ahead
05:24and subtract one instead of adding one.
05:27I'm gonna go ahead and save that.
05:29And that is technically all I need to do,
05:32I believe, to test things out.
05:34Now inside of our testing here, um, we want to,
05:37this is obviously not true anymore,
05:40but in this case we want to create new stepping tests.
05:43So let's go ahead for this test.
05:44Let's go ahead for, let's say index.
05:47Um, oh, let's do index zero.
05:52And if it's an index zero, then we want it to be 1 0 0.
05:55That would be the value that we would expect to have.
05:58And let's go ahead step down
06:00and for step down, let's do it for index, uh, one,
06:04and in this case it would be 1 0, 1, uh,
06:08minus one and zero.
06:10So let's go ahead and save this and let's just make sure
06:12that we're getting what we expect it to do.
06:15So first of all, now we're seeing a few errors,
06:17so we definitely wanna start fixing them.
06:19So let's start with our test, uh, with our store errors.
06:22So let's see, array minus array, plus array.
06:26So first of all, we're seeing here
06:28that we're expecting an empty array,
06:29but we're getting three items inside.
06:32And that is because on the top here we assume
06:34that our array will be empty.
06:36Okay? So that is fixed, that is true.
06:39Let's see what's our next failure?
06:40So we have your one failure, let's, it's
06:43inside of our app test.
06:45And inside of our app test, we cannot read the property.
06:48Zero of undefined rendering without crashing.
06:53So let's go ahead and try to figure out what's going on.
06:55So inside of our app test,
06:57we know we didn't do anything really in here
06:59so it wouldn't be here.
07:01Although what is more probable that's happening is
07:04because in our app itself,
07:05we've included now Oso in our index.
07:08That is in our index.
07:11We've included now our data source
07:13and have not added any data source into our app itself when
07:18we're doing our app test.
07:19So what's going on here is
07:21that our app is directly being rendered here without
07:25actually getting the data that is expecting to get.
07:29So technically speaking, what I'm gonna have
07:31to do is I'm gonna go into my index here
07:33and I'm gonna grab our store information
07:36and just put that into our test here to make sure
07:38that our test oso has our store data.
07:41And next I'm gonna make sure
07:42that it's oso getting our data feed.
07:45So lemme just go ahead and do that and, and,
07:51and save that and let's see if
07:52that fixes our testing problem.
07:54And there we go. And now we passed all of our tests.
07:57Time for us to check it out in a browser.
07:59So let's see what's going on.
08:00So in our browser, and by the way, we're in 2.4,
08:03let me just change that just for the sake of
08:06my eyes at two, four.
08:09Love it. Okay, so in two that four, if I do plus now first
08:14of all, okay, we're having a problem.
08:15So first of all, we cannot read properties, props of null
08:18and that is completely true.
08:19Why is that true inside of our counter itself?
08:22What's happening right now is now
08:24that we're actually using the step up, there is no access
08:27to this because recall if in chapter one we said we needed
08:31to create a constructor,
08:43we needed to create a constructor.
08:45And in our structor itself, we first of all,
08:49every time we do that, we call super props.
08:54And then we would go ahead
08:55and set our, this step up
09:00equals this step up bind to this, making sure
09:04that we don't lose our this.
09:06And we would do the exact same thing, O2 for our step down.
09:09So in the case of step down, I will do the same
09:14and I will do the same.
09:16And then go ahead and save it.
09:18And if we go back into our browser now,
09:19then if I type constructor correctly,
09:22then our item will singularly work.
09:25Same applies oso for each one of these counters.
09:28We'll, we'll work separately as they should.
09:31Alright, so let's do a very big overview
09:35of everything we've done so far.
09:37So let's start from the store itself.
09:39We changed our store to work with arrays
09:41and we said that we never want
09:42to actually physically change our state anytime it's an
09:46actual object and not a number.
09:48Wait, when it's not a primitive value,
09:50we don't wanna change.
09:51Well, we don't wanna change objects period.
09:53So we basically want to create a new object.
09:55We've seen how to do that with arrays now.
09:58And what we do is basically in the, in the,
10:00in this scenario is basically duplicate our array
10:02and then make the change that we wanna make, making sure
10:05that we have a unique copy all the time.
10:07Now, by the way, in this scenario where I was splitting
10:10and breaking, this was kind of an overkill.
10:13I could have just made a duplicate of our array
10:15and then just made a change in the
10:17specific index that I wanted.
10:18This is probably not the most efficient way to do it,
10:21but I wanted to show you that process of
10:23that cutting and splitting.
10:25In real world scenario, I would just take the state
10:28and make a unique copy of it.
10:30And once I made the unique copy, then go ahead
10:32and make that specific change.
10:33That could be your little homework assignment.
10:37The next step is in our step down.
10:38So we did that first step up, we did that first step down.
10:41And again, that is our disclaimer.
10:42This is not the most efficient way to do this.
10:44This is really just 'cause I wanted
10:46to show you how to do this.
10:48Okay, the next step is once we have our data,
10:51we're modifying a new object, a new reference,
10:54a new array into our element
10:56for stepping up and stepping down.
10:59The next step was we tested it out inside of our tests,
11:02making sure that we're using two equal instead
11:05of using the two B,
11:06because we wanna compare between different objects.
11:09Beyond that, we also use the natively builtin object freeze
11:13that exists since ES six.
11:16That helps us test to make sure
11:17that our object cannot be changed.
11:19So in our testing environment, we froze the object
11:22to make sure that it cannot change
11:24as we were testing things out.
11:25Um, and this is a very, very good idea to do in general
11:28because you don't want to by mistake, make a change.
11:31'cause those changes could be very determinant. Basically.
11:33They could be horrible for your application.
11:36And because we changed the name of counter to counters,
11:38we had to make sure that we changed it out.
11:40So here we had to make sure that, uh, as we sent in our data
11:44inside of our app, now that it is an array itself,
11:47that we split it and sent in our array's values one by one
11:51to our counters and setting an index
11:53to our counters as well.
11:55Beyond that, within our counters itself,
11:57we reintroduce our constructor, uh, to make sure
12:00that it still has a this 'cause.
12:02Now we're actually doing a real action
12:04inside a step up again.
12:05And here we send in our index as well, making sure
12:08that our counter will know what index needs to change.
12:12So that is all the changes that we've done.
12:14And through that we've managed
12:16to create three unique counters that stand on their own.
12:23In this lecture we talked about
12:24and saw how to implement our reducer without overriding the
12:28state, but instead of that creating each time a new state.
12:32In the next lecture, we'll continue down the path
12:34as we introduce osu, the Reduce method,
12:37which was introduced in ES six to arrays.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!