Subrata Banerjee
Subrata Banerjee

Reputation: 35

Class object not working properly in reducer

I have a user model (es6 class) and I'm creating a object using the new keyboard and passing that to the initialState to my userReducer function. How can I update the model based on action.

E.g. If I try to dispatch an action to change the isLogging in userModel then the prevState and nextState is same in logger.

https://i.ibb.co/0CBSZ5v/Screenshot-from-2019-04-19-19-07-44.png

User Reducer

import { USER } from '../constants'
import type { IUserInitialState, IUserAction } from '../types'
import { UserModel } from '../models'

const initialState: IUserInitialState = new UserModel()

export const userReducer = (state: IUserInitialState = initialState, action: IUserAction): Object => {
    console.log(state)
    switch (action.type) {
        case USER.LOGIN_REQUEST:
            console.log(state)
            initialState.userIsLogging = action.payload
            return initialState
        default:
            return state
    }
}

------------------------------
User Action

export const loginRequest = (type: boolean): Object => {
    return {
        type: USER.LOGIN_REQUEST,
        payload: type
    }
}

User Model

export class UserModel {

user: IUserModel = {
    username: '',
    password: '',
    isLogging: false
}

set userModel(userObject: IUserModel) {
    this.user = userObject
}

set userIsLogging(logging: boolean) {
    this.user.isLogging  = logging
}

get userIsLogging() {
    return this.user.isLogging
}

}



  [1]: https://i.ibb.co/0CBSZ5v/Screenshot-from-2019-04-19-19-07-44.png

Upvotes: 0

Views: 386

Answers (2)

mario.ecc
mario.ecc

Reputation: 150

A reducer must be a pure function. It should returns a new state based on a previous state and an action.

Please do not mutate the previous state. Instead, create a new instance, make the changes you want there and finally returns this new instance.

I would highly recommend you to watch the videos from the redux github page. No better explanation that the one from the redux author.

Upvotes: 0

Doğancan Arabacı
Doğancan Arabacı

Reputation: 3982

You are using reducer wrong.

1- When you create a state, make sure it's just a primitive type without any methods.

2- A reducer is responsible of creating a new state on any action. But you are only returning initial state. You should have something like

case USER.LOGIN_REQUEST:
        console.log(state)
        initialState.userIsLogging = action.payload
        return {
           ...state,
           userIsLogging: action.payload,
        }

3- You might want to check sagas. You don't have to handle all this async logic yourself

Upvotes: 1

Related Questions