2

I have a piece of state in my React & Redux App dealing with authentication. It's a boolean.

I'd like to simplify grabbing this piece of state from the Redux store but can't find examples of this.

Is this approach a bad idea? I know that mutating state is not the correct approach. I'm not sure if this constitutes a mutation though.

import {
  AUTHENTICATED,  
  AUTHENTICATION_ERROR,
  AUTHENTICATION_REMOVE,
  UNAUTHENTICATED,
} from '../actions/types';

let INITIAL_STATE = false

export default function( state = INITIAL_STATE, action) {
  switch(action.type) {
    case AUTHENTICATED:
      return !state

    case UNAUTHENTICATED:
      return state

    case AUTHENTICATION_ERROR:
      return state

    case AUTHENTICATION_REMOVE:
      return !state

    default:
      return state;
  }
}
PrimeTimeTran
  • 1,081
  • 1
  • 10
  • 25
  • If you're authenticated and in some way manages to authenticate again, you're not authenticated? – JLe May 18 '18 at 06:55
  • I guess this would be one edge case. However I was reading about design patterns recently and I really do believe in this saying right here. https://imgur.com/a/tOxt9JX – PrimeTimeTran May 18 '18 at 07:02
  • https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it – JLe May 18 '18 at 08:51

3 Answers3

1

This is perfectly fine. Because you are not mutating anything from the state.

Yes, You are not mutating the state. Because your state is just a boolean value and you are returning the opposite value of your state. But you are not making any change to the state.

const value = true;
console.log(!value) // This will not change the value directly but it just returns false

But try to use a key in the state. In future, if you want to add some more keys. You don't have to do so many changes.

Akhil P
  • 1,182
  • 2
  • 14
  • 24
1

When your state is just a boolean, you aren't actually mutating the state by writing !state, since boolean, string and number values are immutable.

Also it might not be a bad idea to store just a boolean in the reducer state. However you must read You Might not need Redux to undestand more on when you should and should not use redux

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
0

You can try this enhancer redux-named-reducers

Then your reducer is simplified to something like this:

authModule.reduce(AUTHENTICATED, { isAuthenticated: true })
authModule.reduce([UNAUTHENTICATED, AUTHENTICATION_ERROR, 
AUTHENTICATION_REMOVE], { isAuthenticated: false })

Then you can access authentication state from anywhere like this:

getState(authModule.isAuthenticated)

I'm being very strict with the authentication state here to be set only when authenticated, and unset for everything else, but you can adjust as you see fit.