2

I am a bit new to react/redux

From what I understand state is to be immutable in redux, but when searching for component binding examples I keep seeing things such as

<TextField
  id="usernameId"
  value={this.state.username}    
  onChange={this.handleUsernameChange}
/>

public handleUsernameChange = (event: any) => {
        this.setState({
            username: event.target.value
        });
}

To my understanding this is mutating State. When I change the binding to use a global instead. In the callbacks the values are being changed and updated, however the UI is not observing these variables.

I guess this question is just a sanity check. Is this acceptable in redux?

Please note I am not using other libraries at the moment

Code I've tried without using state

   let loginInfomation: ILoginInformation = new LoginInformation;
...
   <TextField
      id="usernameId"
      value={this.loginInformation.username}    
      onChange={this.handleUsernameChange}
    />

    public handleUsernameChange = (event: any) => {
          this.loginInfomation.username = event.target.value
       });
    }
SCFi
  • 512
  • 8
  • 20

2 Answers2

1

Strings are primitive types, and they are immutable by default.
You want to look out from mutating Objects and Arrays which are reference type.

This is OK:

let x = 8;
x = 5; // no mutation here

This is considered mutation:

let arr = [1,2,3];
arr.push(4); // this is mutating the existing array

So with reference types you can create new Objects or arrays:

let arr = [1,2,3];
let arr2 = [...arr, 4]; // creating new array;
Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
  • 1
    Thank you that explains a lot and I suddenly feel like I understand the projects code a lot better – SCFi Sep 22 '18 at 18:32
  • 1
    @SCFi Glad it helps. I recommend reading the answers in this [post](https://stackoverflow.com/questions/13266616/primitive-value-vs-reference-value) for ref vs value – Sagiv b.g Sep 22 '18 at 18:37
0

You can use a Middleware to add Immutability Checkcheck to your code:

In your configureStore.js:

import { createStore, applyMiddleware } from 'redux';
import reducers from '../reducers';
import immutableCheckMiddleWare from 'redux-immutable-state-invariant';

export function configureStore(initialState) { 
     return createStore(
       rootReducer,
       initialState,
       applyMiddleware(immutableCheckMiddleWare())
    )
}
Mselmi Ali
  • 1,139
  • 2
  • 18
  • 28