I have an error coming from my user reducer code. This is what i have done.
export const userReducer = (
state = localStorage.getItem('user') !== undefined
? JSON.parse(localStorage.getItem('user'))
: null,
action
) => {
switch (action.type) {
case 'LOGGED_IN_USER':
return action.payload
case 'LOGOUT':
return action.payload
default:
return state
}
}
I don't know if i'm declaring the state very well. I feel thats where the issue is coming from.
I hve tried to declare my state as
export const userReducer = (
state = localStorage.getItem('user')
? JSON.parse(localStorage.getItem('user'))
: null,
action
) => {
switch (action.type) {
case 'LOGGED_IN_USER':
return action.payload
case 'LOGOUT':
return action.payload
default:
return state
}
}
I still get same error and my page does't load. It renders a blank screen, with the error in the console.
Here's a "safe" JSON parser, that handles a lot of funky/broken/bad/corrupt JSON:
function jparse(str) {
var result = null;
try {
result = JSON.parse(str)
} catch (e) {
// ignore
}
if (!result) {
try {
result = Function('return (' + str + ")")();
} catch(e){
// ignore
}
}
return result;
}
console.log( jparse(null) ); // null
console.log( jparse('{bob:"er"}') ); // {bob: 'er'}
console.log( jparse('{\'bob\':"er"}') );// {bob: 'er'}
console.log( jparse('{bob:}') ); // null
console.log( jparse(0) ); // 0
console.log( jparse(false) ); // false
console.log( jparse(undefined) ); // undefined