I have the following sagas on my app:
import * as type from '../types';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {put, call, delay} from 'redux-saga/effects';
import {registerUserApi, loginUserApi} from '../services/authApi';
import {loginUserSuccess} from '../actions/authAction';
export function* onLoginUser(payload) {
try {
const response = yield call(loginUserApi, payload.user);
if (response) {
yield call(storeToken, response.data.token.api_token);
yield put(loginUserSuccess(response.data));
}
} catch (error) {
yield put({type: type.LOGIN_USER_ERROR, error});
}
}
export function* onRegisterUser(payload) {
try {
const response = yield call(registerUserApi, payload.user);
yield [put({type: type.REGISTER_USER_SUCCESS, response})];
} catch (error) {
yield put({type: type.REGISTER_USER_ERROR, error});
}
}
async function storeToken(token) {
try {
await AsyncStorage.setItem('token', token);
} catch (error) {
console.log('AsyncStorage error during token store:', error);
}
}
Now, I want to create a global function or saga that will run on every screen if they token exist. If the token doesn't exist, it should logout the user and redirect it to the homescreen.
const LoginScreen: React.FC<Props> = navData => {
const navigateTo = (destinationScreen: string) =>
navData.navigation.navigate(destinationScreen);
const dispatch = useDispatch();
const submitHandler = (val: any) => {
dispatch(loginUserAction(val));
};
const checkUserSignedIn = async () => {
try {
let value = await AsyncStorage.getItem('token');
console.log('checkUserSignedIn token >>>', value);
if (value != null) {
navigateTo('HomeScreen');
}
} catch (error) {
console.log(error);
}
};
useEffect(() => {
checkUserSignedIn();
}, []);
Do you have any idea how do I do it? What some sort of steps should I do in order to run it? Please provide examples as well.