skip to Main Content

For example I have following RTX setup:

export interface UserState {
  name: string
}

const initialState: UserState = {
  name: '',
}

const slice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setUserName: (state, action: { payload: string}) => {
      state.name = action.payload
    }
  },
})

export const { setUserName } = slice.actions
export default slice.reducer
export const store = configureStore({
  reducer: {
    user: userReducer,
  }
})

I know that I can use

store.subscribe(() => {
    const currentState = store.getState() 
})

But this is called for all reducers in the store. I want to just listen to user reducer’s name state. Is it possible?

2

Answers


  1. //Add following code
    export const selectUsername = state => state.user;
    
    export const { setUserName } = slice.actions
    export default slice.reducer
    

    useage useSelector

    const username = useSelector(selectUsername).name;
    

    You will be able to get userName

    Login or Signup to reply.
  2. Yes, you can manually extract the state like the example below.

    const selectUserName = (state: RootState) => state.user.name;
    
     
    const unsubscribe = store.subscribe(() => {
      const userName = selectUserName(store.getState());
      console.log("User name changed to:", userName);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search