I have a React app with the following shallow database model, hooked up to Firebase:
{
"users": {
"userid1": {
"Full name": "Patrick Bateman",
},
},
"posts": {
"userid1": {
"post-1": {
text: "Lorem ipsum",
...
},
"post-2": {
text: "Cats sure are swell",
...
},
},
"userid2": {
...
}
}
}
and in React, I'm using the re-base library's syncState() to fetch initial content and keep the local state and firebase in sync.
In the re-base docs and examples, they use syncState() in componentDidMount. This makes sense, but I don't want to sync all the firebase posts; only those belonging to the user, so my instinct was to do something like this:
componentDidMount() {
this.refs = base.syncState(`posts/${this.state.uid}`, {
context: this,
state: 'posts',
});
}
The problem here is that this.state.uid is null at this stage in the lifecycle.
My question is this: how do I access the uid when I call syncState?
Here is the rest of my code for reference, show auth too:
init() {
// I need the uid here!!!!!! 😫
console.log(this.state.uid); // null
this.refs = base.syncState(`posts/${this.state.uid}`, {
context: this,
state: 'posts',
});
}
componentDidMount() {
this.unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
window.localStorage.setItem(storageKey, user.uid);
this.setState({
uid: user.uid,
user
});
} else {
window.localStorage.removeItem(storageKey);
this.setState({
uid: null,
user: null,
posts: null,
});
}
});
// re-base firebase sync
this.init();
}
componentWillUnmount() {
base.removeBinding(this.ref);
this.unsubscribe();
}
authenticate = (provider) => {
if (provider === 'twitter') {
provider = new firebase.auth.TwitterAuthProvider();
} else if (provider === 'google') {
provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/plus.login');
}
firebase.auth().signInWithPopup(provider).then((authData) => {
// get the of the firebase.User instance
const user = authData.user;
// Set local storage to preserve login
window.localStorage.setItem(storageKey, user.uid);
// Set the state of the current user
this.setState({
uid: user.uid,
user,
});
}).catch(function(error) {
console.log(error);
});
};
With the above code, my app creates local state correctly:
State
posts: {
post-1: {
...
}
}
but then on firebase, predicately adds them with a null user, since the uid is not available.
database: {
posts: {
null: {
post-1: {
...
}
}
}
}
You can just call this.init() after the state sets. this.setState has a second argument that is a callback. This way you can be sure that the uid will not be null.
Example
this.setState({
uid: user.uid,
user
}, () => {
this.init();
});
Related
I have a react app where I use the useContext and useReducer hooks for the login and storage. While the login part works, what I want achieve is to redirect user to a specific page post successful login. I am using react-router#6 and tried to use useNavigate() to navigate user to particular route though it doesn't seem to work.
const AuthService = async (dispatch) => {
const MSAL_CONFIG = {} // populate MSAL config for Microsoft Graph API for AD auth
const msalInstance = new msal.PublicClientApplication(MSAL_CONFIG);
try {
const loginResponse = await msalInstance.loginPopup(scopes);
var username = loginResponse.account.username;
var userid = username.slice(0, username.indexOf("#"));
const loginData = {
auth_token: loginResponse.idToken,
user: {
name: loginResponse.account.name,
id: userid,
email: username,
},
};
const sessionData = {
user_id: userid,
id_token: loginResponse.idToken,
access_token: loginResponse.accessToken,
}
sessionStorage.setItem("currentUser", JSON.stringify(loginData));
dispatch({ type: "LOGIN_SUCCESS", payload: loginData });
return { loginData: loginData, error: null };
// dispatch({ type: 'LOGIN_SUCCESS', payload: loginData });
//sessionStorage.setItem('currentUser', JSON.stringify(data));
} catch (err) {
console.log("+++ Login error : ", err);
dispatch({ type: "LOGIN_ERROR", error: err });
return { loginData: null, error: err };
}
};
In my header.jsx, I have below code to handle the login button. It makes a call to the above AuthService. The code post AuthService() call, i.e. the if block, doesn't take effect, so user never gets redirected to the dashboard page.
const handleLogin = async () => {
await AuthService(dispatch)
console.log("userDetails.token : " + userDetails.token)
if (Boolean(userDetails.token)) {
navigate("/dashboard");
}
};
If I'm correct in understanding that this AuthService function eventually resolves and that the dispatched LOGIN_SUCCESS action updates the userDetails variable that is selected from the auth context state, then I think you have all that you need and are close to a working solution. The issue is that the userDetails value from the render cycle the handleLogin is called in is closed over in callback scope, it will never be a different value. If the userDetails.token value is falsey when handleLogin is called, it will remain falsey in the entire callback scope.
The AuthService function appears to return the same loginData object that is passed in the dispatched LOGIN_SUCCESS action to the store. handleLogin should await this value and conditionally navigate.
const AuthService = async (dispatch) => {
...
try {
const { account, idToken } = await msalInstance.loginPopup(scopes);
const { name, username } = account;
const userid = username.slice(0, username.indexOf("#"));
const loginData = {
auth_token: idToken,
user: {
name,
id: userid,
email: username,
},
};
...
sessionStorage.setItem("currentUser", JSON.stringify(loginData));
dispatch({ type: "LOGIN_SUCCESS", payload: loginData });
return { loginData, error: null }; // <-- return value
} catch (error) {
dispatch({ type: "LOGIN_ERROR", error });
return { loginData: null, error }; // <-- return value
}
};
const handleLogin = async () => {
const { loginData } = await AuthService(dispatch);
if (loginData && loginData.auth_token) { // or loginData?.auth_token
navigate("/dashboard", { replace: true });
}
};
Hi Stackoverflow Community,
I have a Vue.js application where a user can register. The registration is displayed in three different components. Register 1 (email, password), Register 2 (personal information) and Register 3 (preferences).
I implemented an api post request after the user press register on the first page according to bezkoder: https://www.bezkoder.com/vue-3-authentication-jwt/
What I am trying to do now is instead of register the user directly, I want to save the user data in my vuex store and send the api post request in Register 3 instead of Register 1, when I have all the user information.
Unfortunately, I am not able to create a new state in my store. This is my auth.module.js Code (store):
import AuthService from "../services/auth.service";
const user = JSON.parse(localStorage.getItem("user"));
const initialState = user
? { status: { loggedIn: true }, user }
: { status: { loggedIn: false }, user: null };
export const auth = {
namespaced: true,
state: initialState,
actions: {
login({ commit }, user) {
return AuthService.login(user).then(
(user) => {
commit("loginSuccess", user);
return Promise.resolve(user);
},
(error) => {
commit("loginFailure");
return Promise.reject(error);
}
);
},
logout({ commit }) {
AuthService.logout();
commit("logout");
},
register({ commit }, user) {
return AuthService.register(user).then(
(response) => {
commit("registerSuccess");
return Promise.resolve(response.data);
},
(error) => {
commit("registerFailure");
return Promise.reject(error);
}
);
},
},
mutations: {
loginSuccess(state, user) {
state.status.loggedIn = true;
state.user = user;
},
loginFailure(state) {
state.status.loggedIn = false;
state.user = null;
},
logout(state) {
state.status.loggedIn = false;
state.user = null;
},
registerSuccess(state) {
state.status.loggedIn = true;
},
registerFailure(state) {
state.status.loggedIn = false;
},
},
};
So I need to create a state for my userdata (email, password, preferences) and then an action and a method to save my userdata from Register 1 and 2.
Does someone has a clue how I could implement this? Or do you have a better idea how to create my registration?
Glad for all your tips and tricks :)
I could fix it. I created a new file named "patient.module.js" and there I could set the states. My code is the following:
export const patient = {
namespaced: true,
state: {
email: null,
password: null,
location: [],
specialty: [],
attribute: [],
language: [],
gender: [],
},
actions: {
register({ commit }, patient) {
return new Promise((resolve) => {
commit("setPatientData", patient);
resolve();
});
},
},
mutations: {
setPatientData(state, patient) {
Object.assign(state, patient);
},
},
};
As you can see my user state is null at the beginning but when the user logs in, I need to user id for my action called setFavoriteCrypto
So I can retrieve the specific data that is related to the user connected but since vuex initialize the state every time there's a refresh of the page. the user becomes null
I know there's a package called persist state which is something I could work with.
But I would like to know if there's a different way of managing my user connected without depending on a package?
I am using node.js as my backend for this app.
import Api from '#/services/Api'
import axios from 'axios'
import router from '#/router'
const state = {
localStorageToken: localStorage.getItem('user-token') || null,
token: null,
user: null,
favoriteCrypto: []
}
const mutations = {
setToken(state, token) {
state.localStorageToken = token
state.token = token
},
setUser(state, user) {
state.user = user
},
setFavoritecrypto(state, crypto) {
state.favoriteCrypto = crypto
}
}
const actions = {
setToken({commit}, token) {
commit('setToken', token)
},
setUser({commit}, user) {
commit('setUser', user)
},
setFavoriteCrypto({commit}, token) {
if(state.user) {
return Api().get('getuserfavoritescoins', {
params: {
userId: state.user.id
}
})
.then(response => response.data.coins)
.then(cryptoFav => {
commit('setFavoritecrypto', cryptoFav)
})
}
else{
console.log("there's not user state")
}
},
loginUser({commit}, payload) {
return Api().post('login', payload)
.then(response => {
commit('setUser', response.data.user)
commit('setToken', response.data.token)
localStorage.setItem('user-token', response.data.token)
axios.defaults.headers.common['Authorization'] = response.data.token
router.push('/main').catch(e => {})
})
},
logoutUser({commit, dispatch}) {
localStorage.removeItem('user-token')
commit('setUser', null)
commit('setToken', null)
delete axios.defaults.headers.common['Authorization']
}
}
const getters = {
isAuthenticated: state => !!state.localStorageToken,
}
export default {
namespaced: true,
state,
getters,
actions,
mutations
}
I'm new to Vue, i'm just trying to figure out how it is working.
I use router and i have a parent and a child element.
In the child, i have this simple HTML element in the child component:
<button #click="consoleLog">consoleLog</button>
The store at the main.js have this action:
export const store = new Vuex.Store({
state: {
userName: undefined,
password: undefined,
authenticated: false
},
mutations: {
changeUserNameMutation(state, userName) {
state.userName = userName;
},
changePasswordMutation(state, password) {
state.password = password;
Vue.axios.defaults.headers['Authorization'] = password;
},
changeAuthenticatedMutation(state, isAuthenticated) {
state.authenticated = isAuthenticated;
}
},
actions: {
changeUserName({ commit }, userName) {
commit('changeUserNameMutation', userName);
},
changePassword({ commit }, password) {
commit('changePasswordMutation', password);
Vue.axios.defaults.headers['Authorization'] = password;
},
changeAuthenticated({ commit }, isAuthenticated) {
commit('changeAuthenticatedMutation', isAuthenticated);
},
consoleLog({ commit }) {
console.log('sad');
}
}
Nothing more really in the main.js, just the new Vue call, Vue.use() calls and the imports.
In the child component, i have this actions:
methods: {
changeUserName(userName) {
store.dispatch('changeUserName', userName);
},
changePassword(password) {
store.dispatch('changePassword', password);
},
login() {
this.axios.get('http://localhost:3050/admin/login')
.then((data) => {
console.log(data);
})
.catch(() => {
console.log(data);
});
},
...mapActions(['consoleLog'])
}
The first 2 dispatch working, but when i hit the consoleLog method, it's says:
Cannot read property 'dispatch' of undefined at VueComponent.mappedAction
I've tried all other way to call ...mapActions(), but not working this way somehow for me.
(this is my first day in Vue, trying how it's working)
I am trying to render different UIs depending on whether a user is a retailer or not. I think I have mostly everything correct, but when the app initializes, I want to check whether the user is a retailer or not (This dispatches the checkAuth action).
I try running the following to get the value of the isRetailer property from Firebase.
firebase.database().ref('/users/' + user.uid + '/isRetailer').once('value').then(snapshot => snapshot.val()
Then I dispatch some actions based on the result. For some reason, the isRetailer part of my Vuex state is not updating from false even when the users isRetailer property is true.
I'm not really sure why but I'm guessing it has something to do w/ my firebase reference. My full code is below. Thanks!
import firebase from 'firebase'
const authentication = {
state: {
isAuthed: false,
authId: '',
isRetailer: false
},
mutations: {
authUser (state, user) {
state.isAuthed = true;
state.authId = user.uid;
},
notAuthed (state) {
state.isAuthed = false;
state.authId = '';
state.isRetailer = false
},
isRetailer (state) {
state.isRetailer = true
},
isNotRetailer (state) {
state.isRetailer = false
}
},
actions: {
checkUser (context, user) {
if (!user.uid) {
// Do nothing.
} else if (firebase.database().ref('/users/' + user.uid + '/isRetailer').once('value').then(snapshot => snapshot.val()) === true) {
context.commit('authUser', user);
context.commit('isRetailer');
} else {
context.commit('authUser', user);
context.commit('isNotRetailer');
};
},
signOut (context) {
context.commit('notAuthed')
},
setRetailer (context, payload) {
// Set retailer info in Firebase.
var uid = payload.user.uid;
firebase.database().ref('/users/' + uid).set({
name: payload.name,
email: payload.email,
location: payload.retailerLocation,
isRetailer: payload.isRetailer
});
},
setNewUser (context, payload) {
// Sets a user in firebase w/ a isRetailer value of false.
var uid = payload.user.uid;
firebase.database().ref('/users/' + uid).set({
name: payload.name,
email: payload.email,
isRetailer: payload.isRetailer
});
}
},
getters: {}
};
export default authentication;
This might be happening because you have given same name to mutation and state variable: isRetailer, I don't have any reference right now, but this might be the case for mutation not triggering, You can try once by setting your mutation by different name such as:
mutations: {
...
...
setIsRetailer (state) {
state.isRetailer = true
},
isNotRetailer (state) {
state.isRetailer = false
}
},
and use this in actions:
actions: {
checkUser (context, user) {
...
...
context.commit('authUser', user);
context.commit('setIsRetailer');
}