react-navigation Cannot read property 'routes' of undefined - react-native

My application to use to react-navigation the router, in accordance with the API method, the following problems:
react-navigation : why 'routes' of undefined ? https://reactnavigation.org/docs/routers
const SimpleApp = TabNavigator({})
const Simple = StackNavigator({
Home: { screen: SimpleApp },
Login: { screen: Login },
})
const defaultGetStateForAction = Simple.router.getStateForAction;
Simple.router.getStateForAction = (action, state) => {
console.log('action ===',action);
console.log('state ===',state);
console.log('......getStateForAction........');
if (true) {
const routes = [
...state.routes,
{key: 'A', routeName: 'Login', params: { name: action.name1 }},
];
return {
...state,
routes,
index: routes.length - 1,
};
}
return defaultGetStateForAction(action, state);
};
export default class App extends Component {
render() {
return (
<Simple />
)
}
}
TypeError:Cannot read property 'routes' of undefined

We are basically overriding the getStateForAction function.
This function is present in the StackRouter file. What it does is check if the initial state is undefined. If it is, it creates it.
StackRouter.js
getStateForAction(
action: NavigationAction,
state: ?NavigationState
): ?NavigationState {
// Set up the initial state if needed
if (!state) {
let route = {};
... // The code present in the file.
}
To learn more about this look into StackRouter.js.
As the state itself is undefined because initial state is not set, ...state.routes in the code is producing the error.
Currently this will work:
Simple.router.getStateForAction = (action, state) => {
console.log('action ===',action);
console.log('state ===',state);
console.log('......getStateForAction........');
// change the condition to check if state exists.
if (state) {
const routes = [
...state.routes,
{key: 'A', routeName: 'Login', params: { name: action.name1 }},
];
return {
...state,
routes,
index: routes.length - 1,
};
}
return defaultGetStateForAction(action, state);
};

Related

Vuex action does not work properly in a vue mounted hook

I'm building a small e-commerce store with an admin panel for myself.
I use Firebase firestore as my backend to store all the user's data.
I have a root 'users' collection with a document for every single registered user and everything else each user has is branching out of the user doc.
Here are firestore commands i perform so you understand the structure better.
db.collection('users').doc(userId).collection('categories').doc(subCategoryId)...
db.collection('users').doc(userId).collection('subcategories').doc(subCategoryId)...
I use Vuex so every time i need to change something on my firestore (update a product category, remove a category etc.), i dispatch an appropriate action.
The first thing any of those actions does is to go ahead and dispatch another action from auth.js that gets the userId.
The problem is that if the action in question should run in a mounted() lifecycle hook, then it fails to grab the userId.
In EditCategory.vue updateCategory action works perfectly well because SubmitHandler() is triggered on click event but in Categories.vue the fetchCategories does not work and spit out an error:
[Vue warn]: Error in mounted hook (Promise/async): "FirebaseError: [code=invalid-argument]: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: null"
Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: null
Which, as far as i understand it, basically tells me that fetchCategories() action's firestore query could not be performed because the userId was not recieved.
After two days of moving stuff around i noticed that errors only occur if i refresh the page. If i switch to other tab and back on without refreshing, then fetchCategories() from Categories.vue mounted() hook works. Placing the code in to created() hook gives the same result.
I think that there is some fundamental thing i am missing about asynchronous code and lifecycle hooks.
Categories.vue component
<template>
<div class="category-main">
<section>
<div class="section-cols" v-if="!loading">
<EditCategory
v-on:updatedCategory="updatedCategory"
v-bind:categories="categories"
v-bind:key="categories.length + updateCount"
/>
</div>
</section>
</div>
</template>
<script>
import EditCategory from '#/components/admin/EditCategory.vue'
export default {
name: 'AdminCategories',
components: {
EditCategory,
},
data: () => ({
updateCount: 0,
loading: true,
categories: [],
}),
async mounted() {
this.categories = await this.$store.dispatch('fetchCategories');// FAILS!
this.loading = false;
},
methods: {
addNewCategory(category) {
this.categories.push(category);
},
updatedCategory(category) {
const catIndex = this.categories.findIndex(c => c.id === category.id);
this.categories[catIndex].title = category.title;
this.categories[catIndex].path = category.path;
this.updateCount++;
}
}
}
</script>
category.js store file
import firebase, { firestore } from "firebase/app";
import db from '../../fb';
export default {
actions: {
async getUserId() {
const user = firebase.auth().currentUser;
return user ? user.uid : null;
},
export default {
state: {
test: 10,
categories: [],
subCategories: [],
currentCategory: '',
},
mutations: {
setCategories(state, payload){
state.categories = payload;
},
},
actions: {
async fetchCategories({commit, dispatch}) {
try {
const userId = await dispatch('getUserId');
const categoryArr = [];
await db.collection('users').doc(userId).collection('categories').get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
categoryArr.push({ id: doc.id, ...doc.data() })
});
})
commit('setCategories', categoryArr);
return categoryArr;
} catch (err) { throw err; }
},
async updateCategory({commit, dispatch}, {title, path, id}) {
try {
const userId = await dispatch('getUserId');
console.log('[category.js] updateCategory', userId);
await db.collection('users').doc(userId).collection('categories').doc(id).update({
title,
path
})
commit('rememberCurrentCategory', id);
return;
} catch (err) {throw err;}
}
},
}
auth.js store file
import firebase, { firestore } from "firebase/app";
import db from '../../fb';
export default {
actions: {
...async login(), async register(), async logout()
async getUserId() {
const user = firebase.auth().currentUser;
return user ? user.uid : null;
},
},
}
index.js store file
import Vue from 'vue'
import Vuex from 'vuex'
import auth from './auth'
import products from './products'
import info from './info'
import category from './category'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
auth, products, info, category,
}
})
EditCategory.vue
export default {
name: 'EditCategory',
data: () => ({
select: null,
title: '',
path: '',
current: null
}),
props: {
categories: {
type: Array,
required: true
}
},
methods: {
async submitHandler() {
if (this.$v.invalid){
this.$v.$touch()
return;
}
try {
const categoryData = {
id : this.current,
title: this.title,
path: this.path
};
await this.$store.dispatch('updateCategory', categoryData);// WORKS!
this.$emit('updatedCategory', categoryData);
} catch (err) { throw err; }
},
},
//takes current category id from store getter
computed: {
categoryFromState() {
return this.$store.state.currentCategory;
}
},
created() {
console.log('[EditCategory.vue'], currentCategory);
},
mounted(){
this.select = M.FormSelect.init(this.$refs.select);
M.updateTextFields();
},
destroyed() {
if (this.select && this.select.destroy) {
this.select.destroy;
}
}
}
</script>
First of all, it's just a small detail, but you don't need need to make your 'getUserId' action async, since it does not use the 'await' keyword. So can simplify this :
async getUserId() {
const user = firebase.auth().currentUser;
return user ? user.uid : null;
}
const userId = await dispatch('getUserId')
into this :
getUserId() {
const user = firebase.auth().currentUser;
return user ? user.uid : null;
}
const userId = dispatch('getUserId')
Coming back to your id that seems to be undefined, the problem here is that your 'mounted' event is probably triggered before the 'login' can be completed.
How to solve this case ? Actually, there are a lot of different ways to approch this. What I suggest in your case is to use a middleware (or a 'route guard'). This guard can make you are verified user before accessing some routes (and eventually restrict the access or redirect depending on the user privileges). In this way, you can make sure that your user is defined before accessing the route.
This video is 4 years old so it is not up to date with the last versions of Firebas. But I suggest The Net Ninja tutorial about Vue Route Guards with Firebase if you want to learn more about this topic.
Accepted answer actually pointed me to the correct direction.
In my case i had to make a route guard for child routes.
router.vue
import Vue from 'vue'
import Router from 'vue-router'
import firebase from 'firebase/app';
Vue.use(Router);
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
meta: {layout: 'main-layout'},
component: () => import('./views/main/Home.vue')
},
{
path: '/bouquets',
name: 'bouquets',
meta: {layout: 'main-layout'},
component: () => import('./views/main/Bouquets.vue')
},
{
path: '/sets',
name: 'sets',
meta: {layout: 'main-layout'},
component: () => import('./views/main/Sets.vue')
},
{
path: '/cart',
name: 'cart',
meta: {layout: 'main-layout'},
component: () => import('./views/main/Cart.vue')
},
{
path: '/login',
name: 'login',
meta: {layout: 'empty-layout'},
component: () => import('./views/empty/Login.vue')
},
{
path: '/register',
name: 'register',
meta: {layout: 'empty-layout'},
component: () => import('./views/empty/Register.vue')
},
{
path: '/admin',
name: 'admin',
meta: {layout: 'admin-layout', auth: true},
component: () => import('./views/admin/Home.vue'),
children: [
{
path: 'categories',
name: 'adminCategories',
meta: {layout: 'admin-layout', auth: true},
component: () => import('./views/admin/Categories'),
},
{
path: 'subcategories',
name: 'adminSubcategories',
meta: {layout: 'admin-layout', auth: true},
component: () => import('./views/admin/SubCategories'),
},
{
path: 'products',
name: 'adminProducts',
meta: {layout: 'admin-layout', auth: true},
component: () => import('./views/admin/Products'),
},
]
},
{
path: '/checkout',
name: 'checkout',
meta: {layout: 'main-layout'},
component: () => import('./views/main/Checkout.vue')
},
{
path: '/:subcategory',
name: 'subcategory',
meta: {layout: 'main-layout'},
props: true,
params: true,
component: () => import('./views/main/Subcategory.vue')
},
]
})
router.beforeEach((to, from, next) => {
//if currentUser exists then user is logged in
const currentUser = firebase.auth().currentUser;
//does a route has auth == true
const requireAuth = to.matched.some(record => record.meta.auth);
//if auth is required but user is not authentificated than redirect to login
if (requireAuth && !currentUser) {
// next('/login?message=login');
next('login')
} else {
next();
}
})
export default router;
category.js fetchCategories() action
async fetchCategories({commit, dispatch}) {
const userId = await dispatch('getUserId')
try {
const categoryArr = [];
await db.collection('users').doc(userId).collection('categories').get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
categoryArr.push({ id: doc.id, ...doc.data() })
});
})
commit('setCategories', categoryArr);
return categoryArr;
} catch (err) { throw err; }
},

Vue.js Cannot read properties of undefined (reading 'router') error

I'm new to Vue.js and I have created one simple form for the user and storing data using API.
On submit I'm calling this function:
setup(props, { emit }) {
const blankData = {
customer: '',
template: '',
rate: '',
property_from: '',
property_to: '',
move_date: '',
num_days: '',
token: '',
details: '',
customer_options: [],
template_options: [],
rate_options: [],
property_from_options: [],
property_to_options: [],
}
const userData = ref(JSON.parse(JSON.stringify(blankData)))
const resetuserData = () => {
userData.value = JSON.parse(JSON.stringify(blankData))
}
const toast = useToast()
const onSubmit = () => {
store.dispatch('app-user/addUser', userData.value)
.then(
response => {
if (response.status === 1) {
this.$router.push({ name: 'edit-user', params: { id: 10 } })
}
toast({
component: ToastificationContent,
props: {
title: response.message,
icon: response.toastIcon,
variant: response.toastVariant,
},
})
},
error => {
console.log(error)
},
)
}
const {
refFormObserver,
getValidationState,
resetForm,
} = formValidation(resetuserData)
return {
userData,
onSubmit,
refFormObserver,
getValidationState,
resetForm,
}
},
And trying to redirect the user to the edit page after user creation but I'm getting this error and not redirecting:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'router')
I have tried with this stackoverflow answer but getting same error:
const onSubmit = () => {
const self = this
store.dispatch('app-user/addUser', userData.value)
.then(
response => {
if (response.status === 1) {
self.$router.push({ name: 'edit-user', params: { id: 10 } })
}
},
error => {
console.log(error)
},
)
}
Any idea what I'm doing wrong in my code?
You're using Vue 3 and a setup function; there is no this in a setup function.
See Accessing the Router and current Route inside setup.
Untested, but probably something like this will work:
setup() {
const router = useRouter()
const onSubmit = () => {
// ... code omitted ...
router.push({ name: 'edit-user', params: { id: 10 } })
}
return {
onSetup,
// other stuff...
}
}
I think this might be help
router with composition api
https://next.router.vuejs.org/guide/advanced/composition-api.html

Nuxt asyncData result is undefined if using global mixin head() method

I'm would like to get titles for my pages dynamically in Nuxt.js in one place.
For that I've created a plugin, which creates global mixin which requests title from server for every page. I'm using asyncData for that and put the response into storage, because SSR is important here.
To show the title on the page I'm using Nuxt head() method and store getter, but it always returns undefined.
If I place this getter on every page it works well, but I would like to define it only once in the plugin.
Is that a Nuxt bug or I'm doing something wrong?
Here's the plugin I wrote:
import Vue from 'vue'
import { mapGetters } from "vuex";
Vue.mixin({
async asyncData({ context, route, store, error }) {
const meta = await store.dispatch('pageMeta/setMetaFromServer', { path: route.path })
return {
pageMetaTitle: meta
}
},
...mapGetters('pageMeta', ['getTitle']),
head() {
return {
title: this.getTitle, // undefined
// title: this.pageMetaTitle - still undefined
};
},
})
I would like to set title in plugin correctly, now it's undefined
Update:
Kinda solved it by using getter and head() in global layout:
computed: {
...mapGetters('pageMeta', ['getTitle']),
}
head() {
return {
title: this.getTitle,
};
},
But still is there an option to use it only in the plugin?
Update 2
Here's the code of setMetaFromServer action
import SeoPagesConnector from '../../connectors/seoPages/v1/seoPagesConnector';
const routesMeta = [
{
path: '/private/kredity',
dynamic: true,
data: {
title: 'TEST 1',
}
},
{
path: '/private/kreditnye-karty',
dynamic: false,
data: {
title: 'TEST'
}
}
];
const initialState = () => ({
title: 'Юником 24',
description: '',
h1: '',
h2: '',
h3: '',
h4: '',
h5: '',
h6: '',
content: '',
meta_robots_content: '',
og_description: '',
og_image: '',
og_title: '',
url: '',
url_canonical: '',
});
export default {
state: initialState,
namespaced: true,
getters: {
getTitle: state => state.title,
getDescription: state => state.description,
getH1: state => state.h1,
},
mutations: {
SET_META_FIELDS(state, { data }) {
if (data) {
Object.entries(data).forEach(([key, value]) => {
state[key] = value;
})
}
},
},
actions: {
async setMetaFromServer(info, { path }) {
const routeMeta = routesMeta.find(route => route.path === path);
let dynamicMeta;
if (routeMeta) {
if (!routeMeta.dynamic) {
info.commit('SET_META_FIELDS', routeMeta);
} else {
try {
dynamicMeta = await new SeoPagesConnector(this.$axios).getSeoPage({ path })
info.commit('SET_META_FIELDS', dynamicMeta);
return dynamicMeta && dynamicMeta.data;
} catch (e) {
info.commit('SET_META_FIELDS', routeMeta);
return routeMeta && routeMeta.data;
}
}
} else {
info.commit('SET_META_FIELDS', { data: initialState() });
return { data: initialState() };
}
return false;
},
}
}

Redux state undefined on function but not on render()

Im using redux and i want to render my main drawer based if an user is logged on or not. I have this 'init' class that will check for that and do it accordingly.
I'll post the code and explain it at the end:
Init.js
const mapStateToProps = (userReducer) => {
return {
...userReducer,
}
}
const mapDispatchToProps = (dispatch) => {
return {
dispatch,
getCurrentUser: () => {
dispatch(getCurrentUser())
}
}
}
class Init extends Component {
constructor(props) {
super(props);
this.props.getCurrentUser()
console.log("TEST>>")
console.log(this.props)
}
chooseInitialRoute() {
const { navigation, user } = this.props;
if (user) {
navigation.dispatch(StackActions.reset(
{ index: 0, key: null, actions: [NavigationActions.navigate({ routeName: 'LoggedDrawer' })] }
))
} else {
navigation.dispatch(StackActions.reset(
{ index: 0, key: null, actions: [NavigationActions.navigate({ routeName: 'UnloggedDrawer' })] }
))
}
}
user_actions.js
export function getCurrentUser() {
return (dispatch) => {
Parse.User.currentAsync().then(function (user) {
if (user) {
dispatch({ type: 'GET_USER', payload: { user } })
} else {
dispatch({ type: 'GET_USER_REJECTED', payload: error })
}
})
}
}
The console.log(this.props) returns undefined if called inside the constructor (same happens when I do console.log(props). But if I call it inside render() I get the props correcly (meaning that I get the correct user object from parse server).
Is there any way to update the props before the render() method? I want to get the 'updated' props on the chooseInitialRoute()
Thanks in advance. If more code is needed let me know.
If console.log(props) is undefined in the constructor this means the component later gets the props via componentWillReceiveProps and i dont know where you call InitialRoute but you might consider putting it in the lifecycle function instead:
componentWillReceiveProps(props) {
const { navigation, user } = props;
if (user) {
navigation.dispatch(StackActions.reset(
{ index: 0, key: null, actions: [NavigationActions.navigate({ routeName: 'LoggedDrawer' })] }
))
} else {
navigation.dispatch(StackActions.reset(
{ index: 0, key: null, actions: [NavigationActions.navigate({ routeName: 'UnloggedDrawer' })] }
))
}
}
Note that if your props are undefined in the constructor then your component may render multiple times before your component finally receives props via componentWillReceiveProps.

Wait for mapped store getter to update child property

I have the following vuex getters
import { isEmpty } from 'lodash'
// if has token, we assume that user is logged in our system
export const isLogged = ({ token }) => !isEmpty(token)
// get current user data
export const currentUser = ({ user }) => user
export const timeLimit = ({ token_ttl }) => token_ttl
export const getToken = ({ token }) => token
I have the following computed Vuex properties in a child component
name: "ProfilePic",
computed: {
...mapGetters(['currentUser']),
url() {
return new String('').concat(window.location.protocol, '//', window.location.hostname , ':8000', '/games/create/?search=player_id:').valueOf()
}
},
mounted(){
console.log(this.currentUser)
},
watch: {
currentUser(value, old){
console.re.log('ok', value, old);
new QRCode(document.querySelector(".profile-userpic"), {
text: this.url + value,
width: 128,
height: 128,
colorDark : "#000000",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
})
}
}
the parent
import ProfilePic from '../../components/general/qrcode.vue'
export default {
name: 'CcDashboard',
methods : {
...mapActions(['checkUserToken', 'setMessage'])
},
computed: {
...mapGetters(['isLogged'])
},
mounted() {
this.checkUserToken().then(tkn => this.$store.dispatch('setMessage', {type: 'success', message: 'Your Game Starts Now!!!!'})).catch(err => this.$store.dispatch('setMessage', {type: 'error', message: ['Your time is up!']}))
},
components: {
'profile-pic': ProfilePic
}
}
Store
Vue.use(Vuex)
export default new Vuex.Store({
state,
mutations,
actions,
modules,
plugins,
getters,
strict: false, //process.env.NODE_ENV !== 'production',
})
I'm using VuexPersist with localforage
localforage.config({
name: 'vuevue'
});
const vuexLocalStorage = new VuexPersist({
key: 'vuex', // The key to store the state on in the storage provider.
storage: localforage, // or window.sessionStorage or localForage
// Function that passes the state and returns the state with only the objects you want to store.
// reducer: state => ({ Collect: state.Collect, Auth: state.Auth}),
// Function that passes a mutation and lets you decide if it should update the state in localStorage.
// filter: mutation => (true)
modules: ['Auth','Collect'],
asyncStorage: true
})
export const RESTORE_MUTATION = vuexLocalStorage.RESTORE_MUTATION
// // create a new object and preserv original keys
export default [...app.plugins, vuexLocalStorage.plugin]
executing console.log on mounted() I get
{__ob__: Observer}current_points: 45email: "qhegmann#jast.com"id: 2name: "Sandrine Cruickshank"total_points: 45__ob__: Observerdep: Dep {id: 20, subs: Array(4)}value: {id: 2, name: "Sandrine Cruickshank", email: "qhegmann#jast.com", current_points: 45, total_points: 45, …}
However,
When running the logic the this.currentUser.id returns undefined rather than a value( which it does)
Is it that I need to "wait" for it to properly populate from the store? or do I need to call it from the $store.dispatch() ?
I guess what you want here is to watch the state of your computed property itemGetter, and when itemGetter is different from null/undefined trigger the method createProductSet ? https://v2.vuejs.org/v2/guide/computed.html
computed : {
...mapGetters([
'itemGetter'
])
},
watch : {
itemGetter(newVal, oldVal) {
if (typeof newVal == null || typeof newVal == undefined)
return
this.createProductSet(newVal)
}
},
methods : {
createProductSet(id){
// logic
}
}
Figured it out and had to do with a bug with one of my packagesenter link description here