Adventures with Redux in React — Part I

Disclaimer: These notes are meant to help me remember parts of the Udemy series that I am currently working on.


Setting Up Redux (Section 10, Lecture 85)

I am using yarn as a packet manager. I have used npm in the past, but I am following the video and yarn is being used. Redux was added through the use of yarn using the following code:

yarn add redux@3.7.2

Once Redux is added, we can use yarn run dev-server to run and be able to use redux. We are using import {...} from '...' to use the library and export createStore. createStore is used to create the store, but what exactly is a store? The Redux docs state that:

a store holds the whole state tree of the application and represents the entire state of a Redux application.

Having a better understanding of a store, we can now define a variable to take advantage of the store. The store will allow us to change the state by dispatching an action to it.

const store = createStore((state = {default_state }) => {
    return state;
});

console.log(store.getState());

My Takeaway

The store tracks changes in data over time. The function that is used in createStore sets the default state and passes it when we return the state.


Using Redux

Dispatching Actions (Section 10, Lecture 86)

Actions allow us to change the Redux store. The code below is the start point for the lecture:

import { createStore } from 'redux';

const store = createStore((state = { count: 0 }) => {
// The state for count is set to a default value of 0. We then return the state when the function is called.
    return state;
});

console.log(store.getState());

Redux actions are objects that are sent to the store and allow changes to the values of the store. The Redux docs state that:

Actions are payloads of information that send data from your application to your store. They are the only source of information for the store.

We will use the actions in the example that we are using to change the count. The object that is passed needs to have an action type that indicates the type of action being performed. The naming convention is to capitalize the action type.

We send the action to the store using the dispatch() method. It allows us to send the action object. The action is the second argument that is passed on to the function when using storeCreate.

import { createStore } from 'redux';

const store = createStore((state = { count: 0 }, action) => {
// The action is passed, and we use the if statement to check the action passed in using dispatch. Given that we have a console.log before the dispatch method is passed, the if statement will use the else and just set the state. After the dispatch is passed, the action is passed and the count is changed.
    if (action.type === 'INCREMENT') {
        return {
            count: state.count +1
        };
    } else {
        return state;
    }
});

console.log(store.getState());

store.dispatch({
type: 'INCREMENT'
});

console.log(store.getState());

Upon adding more action types, the if/else statement can be changed to a switch statement making easier to handle. Making the adjustment does not change the function. The result is the following code before the challenge:

import { createStore } from 'redux';

const store = createStore((state = { count: 0 }, action) => {
    switch(action.type){
    case 'INCREMENT':
        return{
            count: state.count + 1
        };
    case 'DECREMENT':
        return{
            count: state.count -1
        };
    default:
        return state;
    }
});

console.log(store.getState());

store.dispatch({
type: 'INCREMENT'
});

console.log(store.getState());

The challenge for the video is to create the RESET action that reset the count to 0. An action needs to be created with a type of RESET and passed on by the dispatch() method. A case is made in the switch statement to direct what will happen with RESET.

    ...
    case: 'RESET':
        return{
            count: 0
        };
    ...

My Takeaway

The action is sent via the dispatch() method, but what it does is defined in the in the function that is passed into createStore. The switch statement is used to outline the different things that the action will be allowed to do to the state.


coding-lego

Dispatching Actions (Section 10, Lecture 87)

The main objectives for the video are described as 1) watching for changes in the store and 2) dispatching actions to the store.

The subscribed method in Redux adds a change listener that watches for changes to the state. A function is passed into it and is called everytime that the store changes.

        store.subscribe(() => {
        //function to be called when state changes
            console.log(store.getState());
        });

        // Dispatching action will cause the store to change and the function to be called in the subscribe method
        store.dispatch({
            type: 'INCREMENT'
        });
        store.dispatch({
            type: 'INCREMENT'
        });

        // Will result in a console.log with the changed state

To unsubscribe from the store, we invoke the function returned from subscribe by creating a variable and assigning it to the subscribe method: const unsubscribe = store.subscribe(() => { function }). This will call the function and unsubscribe from the store. The state will continue to change, but we will not be notified of the changes.

To make the changes dynamic, we can add to the object created using the dispatch method. We can create incrementBy that will allow the value of increase to be dynamic. It will be passed into the function through action — action.incrementBy. Passing in the dynamic value also means that we need to be careful when it is not passed in. This is avoided by setting a default value in case incrementBy is not passed in.

// A default action is passed in by creating a variable to provide a default value in case it is not passed in.
    const incrementBy = typeof action.incrementBy === 'number' ? action.incrementBy : 1;

My Takeaway

We can add anything that we want to the object that is passed via the dispatch method. Creating incrementBy allows the passing of dynamic data. By taking dynamic data we need to make sure that we account for any cases where the data is not passed. Using the ternary operator helps prevent any issues of ths sort.

Like this article?

Leave a comment

© 2022 All rights reserved

Made with ❤