React-admin: User Identity is not updating the User name in the Appbar instantly - react-admin

I created a custom page which updates the user name. It gets updated successfully both in my controlled TextField component and in the database. But the name doesn't get updated in the Appbar instantly. If I reload the page then the User name gets updated.
I configured my authProvider.getIdentity() as follows in the authProvider.js file
const authProvider = {
......
getIdentity: () => {
try {
const { _id, name } = JSON.parse(localStorage.getItem("auth")).user;
return Promise.resolve({ id: _id, fullName: name });
} catch (error) {
return Promise.reject(error);
}
},
......
};
export default authProvider;
This authProvider gets the name from the localStorage and displays the name fine. Is there any way to call this getIdentity method manually to get the updated user info? My Custom page's fetch API updates the localStorage instantly which gets updated in the Appbar but after a reload. Is there any other way?
In case needed, the fetch API of my custom page is as follows:
fetch('/my-api')..then(...)
.then(
....
localStorage.setItem("auth", JSON.stringify(data)); //-> setting the user value in local Storage
....
})

Related

nuxt 3 onload wait for onAuthStateChange

im trying to use nuxt 3, pinia and firebase on auth transaction in my application
everything is working fine about onAuthStateChange except when I refresh a page. in this case im getting a kind of delay until load the current user data from firebase and set it with pinia store.
At this time i have a store, where i run onAuthStateChange. if has user, I set the data on state, and return this store as a Promisse
currentUser() {
const auth = getAuth()
return new Promise((resolve, reject) => {
onAuthStateChanged(auth, (user) => {
if (user) {
console.log("user", user)
resolve(user)
this.setUser(user)
} else {
console.log("no user")
resolve(undefined)
}
})
})
},
and, I have a plugin, called init, where i call this store.
export default defineNuxtPlugin((nuxtApp) => {
const store = useAuthStore()
store.currentUser()
})
my question is. how can i make my application wait for this transaction before loading all?
just one example of what this cause, is where i using a getter to show or not a login form. the form is appearing in begining, and then desappear if user is loggedin.
<form-signin v-if="!store.loggedin" />
<div v-else>already logged as {{ store.userData.email }}</div>

vue/vuex: Can you re-render a page from another page?

With the first login in my app, users get a possibility to leave their address. When this address is stored, the user are pushed to their dashboard. Second login the user go straight to the dashboard.
I have 2 Vuex states that are updated with the response.data. 'Signed' leads to address page, 'Frequent' leads to 'dashboard'.
//PROMPT.VUE
mounted () {
this.getPrompt()
},
computed: {
promptStatus () {
return this.$store.getters.getPrompt
}
},
methods: {
async getPrompt() {
try{
await //GET axios etc
// push prompt status in Store
let value = response.data
this.$store.commit('setPrompt', value)
if (this.promptStatus === 'signed') {
this.$router.push({path: '/adres'})
}
if (this.promptStatus === 'frequent') {
this.$router.push({path: '/dashboard'})
}
When user leaves the address I reset the vuex.state from 'signed' to 'frequent'.
//ADRES.VUE
//store address
let value = 'frequent'
this.$store.commit('setPrompt', value)
this.$router.push({name: 'Prompt'})
The Vuex.store is refreshed. But the Prompt.vue wil not re-render with the new vuex.status. Many articles are written. Can 't find my solution. Maybe I organize my pages the wrong way.
In views, it is not recommended to mutate data (call commit) outside vuex. Actions are created for these purposes (called from the component using dispatch). In your case, you need to call action "getPrompt" from the store, but process routing in the authorization component. This is more about best practice
To solve your problem, you need to make a loader when switching to dashboard. Until the data is received, you do not transfer the user to the dashboard page
Example
<script lang="ts">
import { defineComponent } from "vue";
export default defineComponent({
name: "DashboardLayout",
components: { ..., ... },
data: () => ({
isLoad: false
}),
async created() {
this.isLoad = false;
try {
await this.$store.dispatch('getData');
this.isLoad = true;
} catch (error) {
console.log(error)
}
}
});
</script>
Data is received and stored in the store in the "getData" action.
The referral to the dashboard page takes place after authorization. If authorization is invalid, the router.beforeEach handler (navigation guards) in your router/index.js should redirect back to the login page.
Learn more about layout in vuejs
Learn more about navigation guards

Navigate to page and trigger some method

My use case:
After saving the changes on the form, I want to navigate the user to the home page and display for a few seconds message about successful saving. How to do this correct?
My method is simplified like this:
async updateOrder() {
try {
await this.updateOrder({order: this.order});
this.$root.$emit("openCompletedMsg", true); <- I try this, but it doesn't work
this.$router.push("/");
} catch (error) {
...
}
},
So I need show q-dialog on the home page, but after saving my order.

vuex getter does not update on another component depending on timing

My app uses
axios to fetch user information from a backend server
vuex to store users
vue-router to navigate on each user's page
In App.vue, the fetch is dispatched
export default {
name: 'app',
components: {
nav00
},
beforeCreate() {
this.$store.dispatch('fetchUsers')
}
}
In store.js, the users is an object with pk (primary key) to user information.
export default new Vuex.Store({
state: {
users: {},
},
getters: {
userCount: state => {
return Object.keys(state.users).length
}
},
mutations: {
SET_USERS(state, users) {
// users should be backend response
console.log(users.length)
users.forEach(u => state.users[u.pk] = u)
actions: {
fetchUsers({commit}) {
Backend.getUsers()
.then(response => {
commit('SET_USERS', response.data)
})
.catch(error => {
console.log("Cannot fetch users: ", error.response)
})
})
Here Backend.getUsers() is an axios call.
In another component which map to /about in the vue-router, it simply displays userCount via the getter.
Now the behavior of the app depends on timing. If I visit / first and wait 2-3 seconds, then go to /about, the userCount is displayed correctly. However, if I visit /about directly, or visit / first and quickly navigate to /about, the userCount is 0. But in the console, it still shows the correct user count (from the log in SET_USERS).
What did I miss here? Shouldn't the store getter see the update in users and render the HTML display again?
Since it's an object Vue can't detect the changes of the properties and it's even less reactive when it comes to computed properties.
Copied from https://vuex.vuejs.org/guide/mutations.html:
When adding new properties to an Object, you should either:
Use Vue.set(obj, 'newProp', 123), or
Replace that Object with a fresh one. For example, using the object spread syntax we can write it like this:
state.obj = { ...state.obj, newProp: 123 }

How do I update the Apollo data store/cache from a mutation query, the update option doesn't seem to trigger

I have a higher order component in my react native application that retrieves a Profile. When I call an "add follower" mutation, I want it to update the Profile to reflect the new follower in it's followers collection. How do I trigger the update to the store manually. I could refetch the entire profile object but would prefer to just do the insertion client-side without a network refetch. Currently, when I trigger the mutation, the Profile doesn't reflect the change in the screen.
It looks like I should be using the update option but it doesn't seem to work for me with my named mutations. http://dev.apollodata.com/react/api-mutations.html#graphql-mutation-options-update
const getUserQuery = gql`
query getUserQuery($userId:ID!) {
User(id:$userId) {
id
username
headline
photo
followers {
id
username
thumbnail
}
}
}
`;
...
const followUserMutation = gql`
mutation followUser($followingUserId: ID!, $followersUserId: ID!) {
addToUserFollowing(followingUserId: $followingUserId, followersUserId: $followersUserId) {
followersUser {
id
username
thumbnail
}
}
}`;
...
#graphql(getUserQuery)
#graphql(followUserMutation, { name: 'follow' })
#graphql(unfollowUserMutation, { name: 'unfollow' })
export default class MyProfileScreen extends Component Profile
...
this.props.follow({
variables,
update: (store, { data: { followersUser } }) => {
//this update never seems to get called
console.log('this never triggers here');
const newData = store.readQuery({ getUserQuery });
newData.followers.push(followersUser);
store.writeQuery({ getUserQuery, newData });
},
});
EDIT: Just realised that you need to add the update to the graphql definition of the mutation.
EDIT 2: #MonkeyBonkey found out that you have to add the variables in the read query function
#graphql(getUserQuery)
#graphql(followUserMutation, {
name: 'follow',
options: {
update: (store, { data: { followersUser } }) => {
console.log('this never triggers here');
const newData = store.readQuery({query:getUserQuery, variables});
newData.followers.push(followersUser);
store.writeQuery({ getUserQuery, newData });
}
},
});
#graphql(unfollowUserMutation, {
name: 'unfollow'
})
export default class MyProfileScreen extends Component Profile
...
this.props.follow({
variables: { .... },
);
I suggest you update the store using the updateQueries functionality link.
See for example this post
You could use compose to add the mutation to the component. Inside the mutation you do not need to call client.mutate. You just call the mutation on the follow user click.
It might also be possible to let apollo handle the update for you. If you change the mutation response a little bit that you add the following users to the followed user and add the dataIdFromObject functionality. link