react native firebase notification cant get token - firebase

i'm trying to send notification with firebase. i wanna get devices token (senderID) but when i run my code the app shut down immediately
please look at my code and tell me where is my mistake
import React,{useEffect} from 'react'
import { View, Text } from 'react-native'
import messaging from '#react-native-firebase/messaging'
const checkToken = async () => {
try {
const fcmToken = await messaging().getToken();
if (fcmToken) {
console.log(fcmToken);
}
} catch (error) {
console.error(error);
}
};
const App = () => {
useEffect(() => {
checkToken()
}, [])
return (
<View>
<Text>sadasdasfdasdafsfdasfdasdafsdf</Text>
</View>
)
}
export default App

Related

Protect pages from not logged in user in Nextjs

I am creating a login page and dashboard for the admin panel using NExtjS and react-redux. Below is the code I have tried. If I login using Id and password I can login and get all the values from the state and everything works fine.
The problem is if I tried to access the dashboard URL directly it says
Cannot read properties of null (reading 'name') how can I redirect the user to the login page instead of getting up to return statement ???
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import dynamic from 'next/dynamic';
const Dashboard = () => {
const { auth } = useSelector((state) => state);
const router = useRouter();
console.log(auth)
// I can get all the objects from state and cookies are set as state for browser reload so everything is fine here.
useEffect(() => {
if (!auth.userInfo && auth.userInfo.role == 'user') {
router.push('/admin');
console.log('I am here');
}
}, []);
return <h1>{auth.userInfo.name}</h1>;
};
export default dynamic(() => Promise.resolve(Dashboard), { ssr: false });
Finally I find the correct way of solving this issue. The correct way was:
export const getServerSideProps = async (context) => {
const session = await getSession({ req: context.req });
if (session) {
return {
redirect: {
destination: '/',
permanent: false,
},
};
}
return {
props: {
session,
},
};
};

Vue + Pinia + Firebase Authentication: Fetch currentUser before Route Guard

Recently I started to use Pinia as a global store for my Vue 3 Project. I use Firebase for the user authentication and am trying to load the current user before Vue is initialized. Ideally everything auth related should be in a single file with a Pinia Store. Unfortunately (unlike Vuex) the Pinia instance needs to be passed to the Vue instance before I can use any action and I believe that is the problem. On first load the user object in the store is empty for a short moment.
This is the store action that is binding the user (using the new Firebase Web v9 Beta) in auth.js
import { defineStore } from "pinia";
import { firebaseApp } from "#/services/firebase";
import {
getAuth,
onAuthStateChanged,
getIdTokenResult,
} from "firebase/auth";
const auth = getAuth(firebaseApp);
export const useAuth = defineStore({
id: "auth",
state() {
return {
user: {},
token: {},
};
},
actions: {
bindUser() {
return new Promise((resolve, reject) => {
onAuthStateChanged(
auth,
async (user) => {
this.user = user;
if (user) this.token = await getIdTokenResult(user);
resolve();
},
reject()
);
});
},
// ...
}})
and this is my main.js file
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import { createPinia } from "pinia";
import { useAuth } from "#/store/auth";
(async () => {
const app = createApp(App).use(router).use(createPinia());
const auth = useAuth();
auth.bindUser();
app.mount("#app");
})();
How can I set the user before anything else happens?
I figured it out. Had to register the router after the async stuff
//main.js
(async () => {
const app = createApp(App);
app.use(createPinia());
const { bindUser } = useAuth();
await bindUser();
app.use(router);
app.mount("#app");
})();

in React-Native, How to send notification when users install app but don't login or sign-up?

I'm writing a project in React-Native for both iOS and Android, I want to send notification automatically when users just install app but don't login or sign-up after 3 days. I'm using firebase cloud data for the project. Is it possible to do that over coding or firebase?
Using Firebase, you can get the FCM token for the device even without them being logged in. You will needs to get their permission to receive notifications though.
import React, { Component } from "react";
import { Text, View } from "react-native";
import firebase from "react-native-firebase";
export default class componentName extends Component {
async componentDidMount() {
this.checkPermission();
}
//1
async checkPermission() {
firebase
.messaging()
.hasPermission()
.then((enabled) => {
if (enabled) {
this.getToken();
} else {
this.requestPermission();
}
});
}
//2
async requestPermission() {
firebase
.messaging()
.requestPermission()
.then(() => {
this.getToken();
})
.catch((error) => {});
}
//3
async getToken() {
fcmToken = await firebase.messaging().getToken();
if (fcmToken) {
//
//
//
//
//
// Call your API here
//
//
//
//
//
//
}
}
render() {
return (
<View>
<Text> Your APP </Text>
</View>
);
}
}

React Native Firebase: how to check authorization?

After calling "createUserWithEmailAndPassword" or "signInWithEmailAndPassword", a property "currentUser" becomes filled in "auth()". It remains full after restarting an application, even if I remove this user from the Firebase console.
How can I check user's authorization when the application starts?
To force the client to "check in" with the server, you would use the User#getIdToken() method by calling firebase.auth().currentUser.getIdToken(true). If the user has been deleted, this should reject with the error code 'auth/user-token-expired'.
From the React Native Firebase Quick Start documentation, I'll use this as the base of the MWE:
import React, { useState, useEffect } from 'react';
import { View, Text } from 'react-native';
import auth from '#react-native-firebase/auth';
function App() {
// Set an initializing state whilst Firebase connects
const [initializing, setInitializing] = useState(true);
const [user, setUser] = useState();
// Handle user state changes
function onAuthStateChanged(user) {
setUser(user);
if (initializing) setInitializing(false);
}
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
if (initializing) return null;
if (!user) {
return (
<View>
<Text>Login</Text>
</View>
);
}
return (
<View>
<Text>Welcome {user.email}</Text>
</View>
);
}
Once the user has logged in or their cached access has been restored, onAuthStateChanged will receive an event with the current user object. Here we add the ID token request.
function onAuthStateChanged(user) {
if (!user) {
// not logged in
setUser(user);
if (initializing) setInitializing(false);
return;
}
user.getIdToken(/* forceRefresh */ true)
.then(token => {
// if here, this user is still authorised.
setUser(user);
if (initializing) setInitializing(false);
}, error => {
if (error.code === 'auth/user-token-expired') {
// token invalidated. No action required as onAuthStateChanged will be fired again with null
} else {
console.error('Unexpected error: ' + error.code);
}
});
}

firebase and gatsby build don't work well together

I get the following error when I try to login:
u.a.auth is not a function
The error is on this line in Login.js:
app.auth().setPersistence(firebase.auth.Auth.Persistence.NONE);
At the top, I have import app from "./base.js";
In base.js, I have
import firebase from 'firebase/app';
var config = {
....
};
var app;
if(firebase.apps && firebase.apps.length > 0) {
app = firebase.apps[0];
} else {
app = firebase.initializeApp(config);
}
export default app;
That's after I run
gatsby build
gatsby serve
Hello here's how I did it. It worked fine:
import React from "react";
import firebase from "firebase";
...
const LoginForm = () => {
const login = values => {
firebase
.auth()
.signInWithEmailAndPassword(values.email, values.password)
.then(() => { firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION);
navigate("/app/profile");
})
.catch(error => {
console.log("do something with the error:", error);
});
}
return(
<form onSubmit={login}>
form details
</form>
);
};
export default LoginForm;

Resources