React Hook useEffect has missing dependencies: 'initializing', 'onAuthStateChanged', and 'user'. Either include them or remove the dependency array - react-native

Don't know what's the issue here.
If anyone know what's the issue here then please help me out.
I am trying to make anyonymous login.
Don't know what's the issue here.
If anyone know what's the issue here then please help me out.
I am trying to make anyonymous login.
const LoginManager = () => {
// Set an initializing state whilst Firebase connects
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useGlobal('user');
// Handle user state changes
function onAuthStateChanged(user) {
setUser(user);
if (initializing) {
setInitializing(false);
}
}
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
// eslint-disable-next-line react-hooks/exhaustive-deps
if (initializing) {
return null;
}
if (!user) {
return auth()
.signInAnonymously()
.then(() => {
console.log('User signed in anonymously');
})
.catch((error) => {
if (error.code === 'auth/operation-not-allowed') {
console.log('Enable anonymous in your firebase console.');
}
console.log(error);
});
} else {
console.log('User already signed in.');
}
}, []);
return null;
};

Related

Setting data from firebase with useState is returning undefined

I am trying to set data for verification purposes. I do set the data then get undefined which is disturbing to me, I've tried to parse it in different shapes, I've used useCallback hook and without any real benefit
const getUserPhone = useCallback(async () => {
console.log('user phone is requested');
await firebase
.database()
.ref(`users/${login.uid}`)
.once(
'value',
async (data) => {
if (data.exists()) {
console.log('found');
await setUserData(data.toJSON());
console.log('data has been set');
} else {
Alert.alert('User not found');
return;
}
},
// I've tried .get() from firebase and
//.then(async (data: IUser) => {await setUserData(data.toJSON()})
// It does the same.
)
.catch((error) => {
return console.error(error);
});
}, [login.uid]);
const handleVerification = useCallback(async () => {
if (alreadyRequested) {
return;
}
await getUserPhone();
try {
console.log(userData); // undefined
if (!userData?.phoneNumber) {
console.log('no phone number is here');
return;
}
...
} catch ...
}, [alreadyRequested, getUserData, userData?.phoneNumber])
Output:
user phone is requested
found
data has been set
undefined
no phone number is here

Expo apple sign in doesnt work in production

Trying to implement apple sign in in my expo managed project and the sign in doesnt work in production. I have followed all the documentations steps. Changed the bundle ID to the right one.
const handleAppleRegister = (dispatch) => async () => {
try {
// await firebase.auth().signOut() // sign out first
const nonce = Math.random().toString(36).substring(2, 10);
return await Crypto.digestStringAsync(Crypto.CryptoDigestAlgorithm.SHA256, nonce)
.then((hashedNonce) =>
AppleAuthentication.signInAsync({
requestedScopes: [AppleAuthentication.AppleAuthenticationScope.FULL_NAME, AppleAuthentication.AppleAuthenticationScope.EMAIL],
nonce: hashedNonce
})
)
.then((appleCredential) => {
const { identityToken } = appleCredential;
const provider = new firebase.auth.OAuthProvider('apple.com');
provider.addScope('email');
provider.addScope('name');
provider.addScope('displayName');
provider.addScope('photoURL');
const credential = provider.credential({
idToken: identityToken,
rawNonce: nonce
});
return Firebase.auth().signInWithCredential(credential).then(async resp => {
console.log(resp)
const currentUserUID = resp.user.uid;
const db = firebase.firestore();
db.collection('users').doc(currentUserUID).set({
email: resp.additionalUserInfo.profile.email,
uid: resp.user.uid,
});
await AsyncStorage.setItem('status', 'apple');
dispatch({ type: 'handleAppleRegister', payload: 'apple' });
});
})
.catch((error) => {
// ...
console.error(error);
});
} catch (e) {
if (e.code === 'ERR_CANCELED') {
// handle that the user canceled the sign-in flow
} else {
// handle other errors
}
}
};
I've searched every where for a solution but with no luck. Anyone knows what is missing here

React Native UseEffect function is not working according to order

I want to get user's current location and set it into AsyncStorage a array. I will do it in the useEffect hook. But the problem is my functions are not working that according to given order. Here are my code
useEffect(() => {
getUserLocation();
setUserLocation();
check();
}, []);
/*Get User's Currunt Location*/
const getUserLocation = () => {
GetLocation.getCurrentPosition({
enableHighAccuracy: true,
timeout: 15000,
})
.then((location) => {
var lt = location.latitude;
var lg = location.longitude;
setlatitude(lt);
setlongitude(lg);
console.log("getUserLocation", lt, lg);
})
.catch((error) => {
const { code, message } = error;
console.warn(code, message);
});
};
/*Set User's Currunt Location to AsyncStorage*/
const setUserLocation = async () => {
try {
await AsyncStorage.setItem("user_location", JSON.stringify(userLocation));
console.log("setUserLocation", userLocation);
} catch (error) {
console.log("error setting user location");
}
};
const check = () => {
AsyncStorage.getItem("user_location", (err, result) => {
if (result !== null) {
console.log("check", result);
setlatitude(result.latitude);
setlongitude(result.longitude);
} else {
console.log("Data Not Found");
}
});
};
Whenever you use .then you are scheduling your code to run at some point in the future, when the promise has completed. So setUserLocation runs before the then of getUserLocation.
Also, it looks like your getUserLocation set react state, which won't be available until the next render. We use effects to manage this.
// Get the location on mount
useEffect(getUserLocation, []);
// Whenever the location updates, set it into storage
useEffect(() => setUserLocation().then(check), [latitude, longitude]);

React Hook does not set on first API call

So I am sure I am messing something up, but I am not super skilled at API.
So I am trying to make an API call to check if the user exists, if user exists then move about business, if not then do other stuff.
So my first call gets the data, and the user DOES exist, the hook is setting to true, however in my log it fails and the next API is ran. However if I do it a 2nd time, it is true...
What am I doing wrong.
const handleSubmit = async () => {
const data = await axios
.get(`URL`, {
})
.then((resp) => {
if (resp.data.user.name) {
setCheckUser(true);
console.log(resp.data.user.name);
}
return data;
})
.catch((err) => {
// Handle Error Here
console.error(err);
});
console.log(checkUser);
if (!checkUser) {
console.log('No User Found');
//Do Stuff//
}
};
I think the problem here is that setCheckUser(true) is an async operation, so there is no guarantee that the checkUser variable will turn to true right away.
Maybe you can solve this by using a useEffect block like this
//somewhere on the top of your file, below your useState statements
useEffect(()=> {
if (!checkUser) {
console.log('No User Found');
//Do Stuff//
}
}, [checkUser])
const handleSubmit = async () => {
const data = await axios
.get(`URL`, {
})
.then((resp) => {
if (resp.data.user.name) {
setCheckUser(true);
console.log(resp.data.user.name);
}
return data;
})
.catch((err) => {
// Handle Error Here
console.error(err);
});
};

Is User already have Permissions FB SDK react native

I have a simple Question i just want to know that is user first time trying to logged in or else.
I am using react native fb SDK and Im enable to find any way.
I already try but not getting success.
AccessToken.getCurrentAccessToken()
Thanks
This is my login facebook function:
Step is:
Get permission
User login
Get token
My code:
import { LoginManager, AccessToken } from 'react-native-fbsdk';
const loginFacebook = () => {
setTypeLogin(TYPE_LOGIN.FACEBOOK)
if (Platform.OS === "android") {
LoginManager.setLoginBehavior("web_only")
}
LoginManager.logInWithPermissions(['public_profile', 'email']).then(
function (result) {
if (result.isCancelled) {
} else {
AccessToken.getCurrentAccessToken()
.then((data) => {
setAccessToken(data.accessToken)
prepareCallApi()
})
.catch(error => {
console.log(error)
})
}
},
function (error) {
console.log('Login fail with error: ' + error);
},
);
};