I am getting data from local storage and wanna dispatch a redux function.
But I think the action is not calling the try block
in the function.
In the redux
export function testLogin(loginStatus) {
return async dispatch => {
try {
alert('me here')
dispatch({
type: TEST_LOGIN_STATUS,
payload: loginStatus,
});
} catch (error) {
console.log('not logged in');
}
};
}
export const authReducer = (state = initialState, action) => {
switch (action.type) {
case LOGGED_IN:
return {...state, token: action.payload, loggedIn: true};
case TEST_LOGIN_STATUS:
return {...state, loggedIn: action.payload};
default:
return state;
}
};
as you can see I am getting the status as param for testLogin
action function.
Here is what I am doing in the Home screen.When user open the app. I need to test if the user is logged in or not by checking the local storage
useEffect(() => {
async function getStorageValue() {
let value;
try {
value = await AsyncStorage.getItem('isLoggedIn');
if (value === 'true') {
dispatch(testLogin(true));
} else {
dispatch(testLogin(false));
}
} catch (e) {
// handle here
} finally {
}
}
getStorageValue();
}, []);
Since Async storage
accept only strings
in am testing the value and returning true or false.
The thing is even if I am logged in. The when I check the redux loginStatus
I am always logged out
. Is there anything wrong with dispatch function?
CodePudding user response:
It looks like testLogin
is a higher order function. i.e. it returns a function that accepts dispatch as an argument.
In your useEffect
try
block try the following:
testLogin(value === 'true')(dispatch)
(replacing the if/else)
CodePudding user response:
Correct me if I am wrong. But are you targeting the testLogin correctly?
For example I've seen this issue before and people simply forgot to target the Action correctly.
For example an object named LoginActions.
const LoginActions = {... testLogin(loginStatus) { ...} }
And then in the Code where I want to dispatch
import { LoginActions } from "../store/LoginActions" //<-- Import here
useEffect(() => {
async function getStorageValue() {
let value;
try {
value = await AsyncStorage.getItem('isLoggedIn');
if (value === 'true') {
dispatch(LoginActions.testLogin(true)) //<-- Dispatch here.
} else {
dispatch(LoginActions.testLogin(false));
}
} catch (e) {
// handle here
} finally {
}
}
getStorageValue();
}, []);
Again, I might have misunderstood but I was just wondering if this was the case?