webmastx
webmastx

Reputation: 683

Redux : store.getState return undefined value

Why my store.getState return undefined value! I'm quite new with ReactJS & Redux here my code

import {createStore} from 'redux';

const initialState = {
salary: 1000,
}

const reducer = (state=initialState, action) => {
switch (action.type) {
    case "ADD":
        state = {
            salary: state.salary+=action.payload,
        }
        break;

    default:
        break;
}
}

const store = createStore(reducer);

store.subscribe(() => {
console.log('Update salary: ', store.getState.salary);
})

store.dispatch({
type: "ADD",
payload: 2000,
});

Console : Update salary: – undefined

Thank you.

Upvotes: 6

Views: 11701

Answers (3)

webmastx
webmastx

Reputation: 683

By returning the state value solved the problem!

switch (action.type) { 
case "ADD": 

return { salary: state.salary+= action.payload } 
break; 

default: break; } 

Upvotes: 1

Ursus
Ursus

Reputation: 30056

getState is a method, call it

console.log('Update salary: ', store.getState().salary);

And you should fix even your reducer

case "ADD":
   return {salary: state.salary + action.payload}

It has to return the new state, you don't return anything

Upvotes: 4

Farhan Haque
Farhan Haque

Reputation: 1011

You should not modify the state directly as done in case "ADD". Instead return a new state. Use code

case "ADD":
    return {
        salary: state.salary+=action.payload
    }

also use store.getState().salary to retrieve the data.

This will work. I hope it helps.

Upvotes: 1

Related Questions