Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

00:25:48 | INFO : Cannot read property 'userService' of undefined #34147

Closed
Aakash359 opened this issue Jul 6, 2022 · 1 comment
Closed

00:25:48 | INFO : Cannot read property 'userService' of undefined #34147

Aakash359 opened this issue Jul 6, 2022 · 1 comment

Comments

@Aakash359
Copy link

00:25:48 | INFO : Cannot read property 'userService' of undefined
i have upgrade the react native version from 62 to 69.0.1 and my code is written in Typescript with Mob X and class based so i am getting this error even
i imported correctly i think ... as i am new in typescript so i don't have much idea about it

Steps to reproduced
00:25:48 | INFO : Cannot read property 'userService' of undefined
This is my packg.json file
{
"name": "Conexus",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint .",
"postinstall": "patch-package"
},
"dependencies": {
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/plugin-proposal-decorators": "^7.18.6",
"@babel/plugin-transform-flow-strip-types": "^7.18.6",
"@react-native-async-storage/async-storage": "^1.17.7",
"@react-native-community/masked-view": "^0.1.11",
"@react-native-community/netinfo": "^9.3.0",
"@react-native-community/push-notification-ios": "^1.10.1",
"@types/react-image-gallery": "^1.0.5",
"@types/stack-utils": "^2.0.1",
"appcenter": "^4.4.4",
"appcenter-analytics": "^4.4.4",
"appcenter-crashes": "^4.4.4",
"autobind-decorator": "^2.4.0",
"axios": "^0.27.2",
"babel-preset-react-native": "^4.0.1",
"deprecated-react-native-prop-types": "^2.3.0",
"jetifire": "^1.2.6",
"lodash": "^4.17.21",
"mobx": "^5.15.4",
"mobx-logger": "^0.7.1",
"mobx-react": "^5.4.4",
"mobx-state-tree": "^3.10.2",
"moment": "^2.29.3",
"native-base": "^3.4.7",
"patch-package": "^6.4.7",
"postinstall-postinstall": "^2.1.0",
"react": "^18.2.0",
"react-native": "0.69.1",
"react-native-cached-image": "^1.4.3",
"react-native-calendars": "^1.1284.0",
"react-native-code-push": "^7.0.4",
"react-native-datepicker-dialog": "^0.0.9",
"react-native-device-info": "^9.0.2",
"react-native-fit-image": "^1.5.5",
"react-native-gesture-handler": "^2.5.0",
"react-native-image-gallery": "^2.1.5",
"react-native-incall-manager": "^4.0.0",
"react-native-keep-awake": "^4.0.0",
"react-native-linear-gradient": "^2.5.6",
"react-native-logs": "^4.0.1",
"react-native-onesignal": "^4.3.11",
"react-native-permissions": "^3.4.0",
"react-native-push-notification": "^8.1.1",
"react-native-reanimated": "^2.8.0",
"react-native-router-flux": "^4.2.0",
"react-native-safe-area-context": "^4.3.1",
"react-native-screens": "^3.13.1",
"react-native-slider": "^0.11.0",
"react-native-sortable-list": "^0.0.25",
"react-native-sound": "^0.11.2",
"react-native-svg": "^12.3.0",
"react-native-system-setting": "^1.7.6",
"react-native-timer": "^1.3.6",
"react-native-vector-icons": "^9.2.0",
"rn-viewpager": "^1.2.9"
},
"devDependencies": {
"@babel/core": "^7.18.6",
"@babel/plugin-proposal-class-properties": "^7.18.6",
"@babel/runtime": "^7.18.6",
"@react-native-community/eslint-config": "^3.0.3",
"@types/jest": "^28.1.3",
"@types/react": "^18.0.14",
"@types/react-native": "^0.69.1",
"@types/react-test-renderer": "^18.0.0",
"babel-jest": "^28.1.2",
"eslint": "^8.18.0",
"jest": "^28.1.2",
"metro-react-native-babel-preset": "^0.71.2",
"patch-package": "^6.4.7",
"react-test-renderer": "17.0.2",
"typescript": "^4.7.4"
},
"jest": {
"preset": "react-native"
}
}
This is my user store file :
import { types, flow, getSnapshot } from 'mobx-state-tree'
import { Actions } from 'react-native-router-flux'
import OneSignal from 'react-native-onesignal'
import * as _ from 'lodash'
import { showApiErrorAlert } from '../common'
import { IUser, rest, userService, setConexusApiEnvironment, getConexusApiEnvironment, ApiEnvironment, IRegisterUser } from '../services'
import { logger } from 'react-native-logs'
import { ScreenType } from '../common/constants'
import { deviceStore } from './deviceStore'
import { conversationStoreInstance } from '../stores/message-center'
import { Alert } from 'react-native'
import AsyncStorage from '@react-native-async-storage/async-storage';

const log = logger.createLogger()
export const UserFacilityModel = types.model('UserFacility', {
facilityName: types.optional(types.string, ''),
facilityId: types.optional(types.string, ''),
photoUrl: types.optional(types.string, ''),
manager: types.model('UserFacilityManager', {
acctManagerName: types.optional(types.string, ''),
acctManagerPhone: types.optional(types.string, ''),
acctManagerPhotoUrl: types.optional(types.string, '')
})
}).actions(self => {
return {
sendMessage: flow(function* (messageText: string) {
return yield rest.post('facility/insertFacilityNote', {
note: messageText,
facilityId: self.facilityId
})
}),
sendFeedback: flow(function* (messageText: string) {
return yield rest.post('facility/insertAppFeedback', {
note: messageText,
facilityId: self.facilityId
})
})
}
})

const User = types.model('User', {
userId: types.string,
username: types.optional(types.string, ''),
firstName: types.optional(types.string, ''),
lastName: types.optional(types.string, ''),
title: types.optional(types.string, ''),
photoUrl: types.union(types.string, types.undefined),
userType: types.optional(types.string, ''),
userTypeId: types.optional(types.string, ''),
phoneNumber: types.optional(types.string, ''),
userFacilities: types.optional(types.array(UserFacilityModel), []),
})

export type UserCredentials = { username: string, password: string, environment: ApiEnvironment }
export type ProfileUpdateDetails = { firstName: string, lastName: string, title: string }
export const USER_STORE_AUTH_TOKEN_STORAGE_KEY = '@user'
export const USER_STORE_PROFILE_EDITED_STORAGE_KEY = '@PROFILE_EDIT_VIEWED'

const UserStore = types
.model('UserStore', {
user: types.union(User, types.undefined),
selectedFacilityId: types.optional(types.string, ''),
isRecoveringPassword: types.optional(types.boolean, false),
isAuthenticating: types.optional(types.boolean, false),
isSavingProfile: types.optional(types.boolean, false),
inWalkthroughMode: types.optional(types.boolean, false)
})

.views(self => {
    return {
        get isLoggedIn(): boolean { return !!(self.user && self.user.userId) },

        get isFacilityUser(): boolean {
            if (!self.user) {
                return false
            }
            const userType = (self.user.userType || 'HCP').toUpperCase()
            return userType === 'HCP' ? false : true
        },

        get selectedFacility(): typeof UserFacilityModel.Type | null {
            if (this.user) {
                return this.user.userFacilities.find(uf => {
                    return uf.facilityId === self.selectedFacilityId
                })
            }

            return null
        },

        get isNurseUser(): boolean {
            if (!self.user) {
                return false
            }
            const userType = (self.user.userType || 'HCP').toUpperCase()
            return userType === 'HCP' ? true : false
        },
        get homeView(): string {
            if (!self.user) {
                return ScreenType.NURSES.HOME
            }
            const userType = (self.user.userType || 'HCP').toUpperCase()
            return userType === 'HCP' ? ScreenType.NURSES.HOME : ScreenType.FACILITIES.REVIEW_HOME
        },
        get shouldShowWalkThrough(): boolean {
            if (!self.user) {
                return false
            }

            return !self.user.photoUrl || !self.user.firstName || !self.user.lastName
        }
    }
})

.actions(self => {

    const actions = {
        setSelectedFacility: (id: string) => {
            if (!self.user) {
                log.info('setSelectedFacility', 'user not available');
            }
            self.selectedFacilityId = id;
        },

        applyUserAuthorizationToken: flow(function* (token: string) {
            rest.defaults.headers.common.Authorization = `Bearer ${token}`
            deviceStore.setAuthToken(token)
            yield AsyncStorage.setItem(USER_STORE_AUTH_TOKEN_STORAGE_KEY, JSON.stringify({token, environment: getConexusApiEnvironment()}))
        }),

        resetAuthorizationToken: flow(function* () {
            delete rest.defaults.headers.common.Authorization
            deviceStore.setAuthToken('')
            yield AsyncStorage.removeItem(USER_STORE_AUTH_TOKEN_STORAGE_KEY)
        }),

        refreshAuthorizationToken: flow(function* () {
            try {
                const data = yield userService.refreshAuthorizationToken()
                yield actions.applyUserAuthorizationToken(data.authToken, getConexusApiEnvironment())
                return true
            } catch (error) {
                log.info('UserStore', 'RefreshAuthToken', 'Error', error)
                self.isAuthenticating = false
                return false
            }
        }),

        initUser: flow<IUser>(function* (user: IUser) {
            log.info('UserStore', 'initUser', user)

            self.user = User.create(user)

            log.info('Subscribe user to oneSignal')
            OneSignal.setSubscription(true);
            OneSignal.syncHashedEmail(user.username)
            
            const tags = {
                'env': getConexusApiEnvironment(),
                'userType': user.userType,
                'userId': user.userId
            }

            OneSignal.sendTags(tags)
            log.info('OneSignal tags', tags)

            log.info('UserStore', 'Loading conversations')
            
            yield conversationStoreInstance.loadUnreadCount()
                .then(
                    (unreadCount) => {
                        log.info('UserStore', 'UnreadCount', unreadCount)
                    }
                )
                .catch((error) => log.info('UserStore', 'LoadUnreadCount', 'error', error))

            self.selectedFacilityId = self.user.userFacilities.length ? self.user.userFacilities[0].facilityId : ''

            const profileEditHistoryString = yield AsyncStorage.getItem(USER_STORE_PROFILE_EDITED_STORAGE_KEY)
            const profileEditHistory = JSON.parse(profileEditHistoryString || '{"edited": false}')

            if (!profileEditHistory.edited && self.shouldShowWalkThrough) {
                self.inWalkthroughMode = true
                return ScreenType.WALKTHROUGH
            }

            return self.homeView

        }),

        logout: flow(function* () {
            log.info('UserStore:Logout', 'Start')

            yield actions.resetAuthorizationToken()
            self.isAuthenticating = false

            try {
                self.user = undefined

                log.info('Unsubscribe user from oneSignal')
                deviceStore.reset()

            } catch { }

            try {
                deviceStore.reset()
            } catch (err) { log.info('UserStore:Logout:Error', err) }

            Actions.reset('root')
            log.info('UserStore:Logout', 'Complete')
        }),

        saveProfile: flow(function* (profile: ProfileUpdateDetails) {
            self.isSavingProfile = true
            try {
                log.info('UserStore:SaveProfile:FormData', JSON.stringify(profile, null, 4))
                const snapShot = getSnapshot(self.user)
                const payload = <IUser>Object.assign({}, snapShot, _.pick(profile, Object.keys(snapShot)))
                
                const saveResult = yield userService.saveProfile(payload)
                log.info('UserStore:SaveProfile:Received', JSON.stringify(saveResult, null, 4))

                self.isSavingProfile = false

                const loadResult = yield userService.getProfile()
                log.info('UserStore:SaveProfile:LoadProfile:Received', loadResult)
                self.user = loadResult

                yield AsyncStorage.setItem(USER_STORE_PROFILE_EDITED_STORAGE_KEY, JSON.stringify({ edited: true }))

                if (self.inWalkthroughMode) {
                    self.inWalkthroughMode = false
                    Actions[self.homeView]()
                } else {
                    Actions.pop()
                }

                return true
            }
            catch (error) {
                self.isSavingProfile = false

                showApiErrorAlert({
                    defaultTitle: 'Save Profile Error',
                    defaultDescription: 'An unexpected error occurred while saving your profile',
                    loggerName: 'UserStore',
                    loggerTitle: 'saveProfile:error',
                    error: error
                })

                return false
            }
        }),
        register: flow<IRegisterUser>(function*(registerData: IRegisterUser){
            log.info('UserStore: ', registerData)
            try{
                const registration = yield userService.register(registerData)
                return registration.Success
            } catch (error) {
                showApiErrorAlert({
                    defaultTitle: 'Registration error',
                    defaultDescription: '',
                    loggerName: 'UserStore',
                    loggerTitle: 'Registration:error',
                    error: error
                })
                log.info(error)
                return ''
            }
        }),
        login: flow<UserCredentials>(function* (credentials: UserCredentials) {
            self.isAuthenticating = true
            console.log("Credetial yanha tak Aa rahe hai",credentials.username, credentials.password);
            
            try {                    
                const user = yield userService.login(credentials.username, credentials.password)
                yield actions.applyUserAuthorizationToken(user.authToken)
                self.isAuthenticating = false
                return actions.initUser(user)

            } catch (error) {
                self.isAuthenticating = false

                showApiErrorAlert({
                    defaultTitle: 'Login Failed',
                    defaultDescription: 'Something went wrong',
                    loggerName: 'UserStore',
                    loggerTitle: 'login:error',
                    error: error
                })

                log.info(error);

                return ''
            }
        }),
        tryLoadTokenFromCache: flow(function* () {
            const data = JSON.parse(yield AsyncStorage.getItem(USER_STORE_AUTH_TOKEN_STORAGE_KEY))
            
            if (data.token && data.token.length) {
                setConexusApiEnvironment(data.environment)                    
                yield actions.applyUserAuthorizationToken(data.token, data.environment)
                actions.refreshAuthorizationToken() // fire and forget (don't care if it fails, just trying to keep it current if possible)
            }
        }),
        tryLoadFromCache: flow(function* () {
            const data = JSON.parse(yield AsyncStorage.getItem(USER_STORE_AUTH_TOKEN_STORAGE_KEY))
            
            if (data.token && data.token.length) {
                setConexusApiEnvironment(data.environment)
                yield actions.applyUserAuthorizationToken(data.token)
                const validToken = yield actions.refreshAuthorizationToken()

                if (validToken) {
                    return yield actions.initUser(yield userService.getProfile())
                } 
            }

            return ScreenType.LOGIN
        }),

        recoverPassword: flow(function* (username: string) {
            self.isRecoveringPassword = true

            try {
                const response = yield userService.recoverPassword(username)
                self.isRecoveringPassword = false
                Alert.alert(response.title, response.description)
                return true

            } catch (error) {
                self.isRecoveringPassword = false

                showApiErrorAlert({
                    defaultTitle: 'Password Recovery Error',
                    defaultDescription: 'An unexpected error occurred while recovering your password. Please try again.',
                    loggerName: 'UserStore',
                    loggerTitle: 'recoverPassword',
                    error: error
                })

                return false
            }
        }),

        setUserImage: (image: string) => { self.user.photoUrl = image }
    }

    return actions
})

export const userStoreInstance = UserStore.create()
export type UserStore = typeof UserStore.Type

This is my user-service file

import { logger } from 'react-native-logs'
import { rest } from './rest'
import { userStoreInstance } from '../stores/index'
import { Platform } from 'react-native'

const log = logger.createLogger()
export interface IUser {
userId?: number
username?: string
firstName?: string
lastName?: string
photoUrl?: string
userType?: string
userTypeId?: number
password?: string
authToken?: string
}
export interface IRegisterUser {
firstName: string,
lastName: string,
company?: string,
title?: string,
eMail: string,
phoneNumber: string,
howHeard: string,
isFacility: boolean
}

export class UserService {

// register(userInfo: IRegisterUser){
// return new Promise((resolve, reject) => {
// // logger.group('api', 'Register new user', log => {
// const payload = userInfo
// log.info('payload', payload)
// rest.post('/user/newRegister', payload)
// .then((res) => {
// log.info('response', res)
// resolve(res.data)
// }, reject)
// // })
// })
// }

login(username, password) {
return new Promise((resolve, reject) => {
// logger.group('api', 'login-with-credentials', log => {
const payload = { username, password, app: true }
log.info('payload', payload)
log.info("Rest default: ", rest.defaults)
// rest.post('/user/login-with-credentials', payload)
// .then((res) => {
// log.info('response', res)
// resolve(res.data)
// }, reject)
// })
})
}

// refreshAuthorizationToken() {
// return new Promise((resolve, reject) => {
// // logger.group('api', 'refresh-authorization-token', log => {

// rest.get('/user/refreshToken')
// .then((res) => {
// log.info('response', res)
// resolve(res.data)
// }, reject)
// // })
// })
// }

// getProfile() {
// return new Promise((resolve, reject) => {
// // logger.group('api', 'get-profile', log => {
// rest.get('/user/current')
// .then((res) => {
// log.info('response', res)
// resolve(res.data)
// },
// reject)
// // })
// })
// }

// saveProfile(profile: IUser) {
// return new Promise((resolve, reject) => {
// // logger.group('api', 'update-profile', log => {
// log.info('payload', profile)
// rest.put('/user/current', profile).then((res) => {
// log.info('response', res)
// resolve(res.data)
// }, reject)
// // })
// })
// }

// savePhoto(photo:string, mimeType: string = 'image/jpg') {
// return new Promise((resolve, reject) => {
// // logger.group('api', 'update-photo', log => {
// let ext = mimeType.split('/')[1] || 'jpg';
// if (ext === 'jpeg') {
// ext = 'jpg';
// }

// const payload = { base64Image: photo, fileExt: ext }
// rest.post('/user/current/base64Photo', payload).then((res) => {
// resolve(res.data)
// }, reject)
// // })
// })
// }

// recoverPassword(username) {
// return new Promise((resolve, reject) => {
// // logger.group('api', 'recover-password', log => {
// const payload = { username }
// log.info('payload', payload)
// rest.post('/user/PasswordRequest', payload).then((res) => {
// resolve(res.data)
// }, reject)
// // })
// })
// }

// updateVideoSession(pollingUserId: string) {
// return new Promise((resolve, reject) => {
// // logger.group('api', 'updateVideoSession', log => {
// const payload = { pollingUserId: pollingUserId }
// log.info('payload', payload)
// rest.post('/user/updateVideoSession', payload).then((res) => {
// log.info('response', res)
// resolve(res.data)
// }, reject)
// // })
// })
// }

// updateDeviceToken(tokenInfo: Object) {
// return new Promise((resolve, reject) => {
// // logger.group('api', 'updateDeviceToken', log => {
// const payload = { ...tokenInfo, deviceType: Platform.OS }
// log.info('payload', payload)
// rest.post('/user/deviceToken', payload).then((res) => {
// log.info('response', res)
// resolve(res.data)
// }, reject)
// // })
// })
// }

// respondPingRequest(pollingUserId: string) {
// return new Promise((resolve, reject) => {
// // logger.group('api', 'updateVideoSession', log => {
// const payload = { pollingUserId }
// log.info('payload', payload)
// rest.post('/user/updateVideoSession', payload).then((res) => {
// log.info('response', res)
// resolve(res.data)
// }, reject)
// // })
// })
// }
}

export const userService = new UserService()

const user = yield userService.login On this line in userstore.ts it's giving error he is not able to find the userService file i don't why
kindly help me to resolve this issues i fed up with this issues

@cortinico
Copy link
Contributor

Closing as you haven't followed the issue template. Please follow the issue template and re-open. Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants