vuex not loading module decorated with vuex-module-decorators - decorator

I get this error when trying to load a store module with the vuex-module-decorators into the initialiser:
vuex.esm.js?2f62:261 Uncaught TypeError: Cannot read property
'getters' of undefined at eval (vuex.esm.js?2f62:261) at Array.forEach
() at assertRawModule (vuex.esm.js?2f62:260) at
ModuleCollection.register (vuex.esm.js?2f62:186) at eval
(vuex.esm.js?2f62:200) at eval (vuex.esm.js?2f62:75) at Array.forEach
() at forEachValue (vuex.esm.js?2f62:75) at ModuleCollection.register
(vuex.esm.js?2f62:199) at new ModuleCollection (vuex.esm.js?2f62:160)
The index.ts file is quite simple and all works until i introduce the modules to the initialiser:
import Vue from 'vue';
import Vuex from 'vuex';
import { AuthenticationModule, IAuthenticationState } from './modules/authentication';
import VuexPersistence from 'vuex-persist';
Vue.use(Vuex);
export interface IRootState {
authentication: IAuthenticationState;
}
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
});
const store = new Vuex.Store<IRootState>({
modules: {
authentication: AuthenticationModule, // if this is not here it works but this will mean the vuex-persist will not work
},
plugins: [vuexLocal.plugin],
});
export default store;
Here is the authentication module i believe is throwing the error:
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators';
import { Generic422, LoginEmailPost, RegisterPost, TokenRenewPost, User, UserEmailPut, UserPasswordPut, UserPut } from '#/api/ms-authentication/model/models';
import { Api } from '#/services/ApiHelper';
import Auth from '#/services/Auth';
import store from '#/store';
export interface IAuthenticationState {
user: User;
authenticated: boolean;
prompt: {
login: boolean,
};
errorRegister: Generic422;
errorLogin: Generic422;
}
const moduleName = 'authentication';
#Module({dynamic: true, store, name: moduleName})
class Authentication extends VuexModule implements IAuthenticationState
{
public authenticated: boolean = false;
public errorRegister: Generic422 = {};
public errorLogin: Generic422 = {};
public prompt = {
login: false,
};
public user: User = {
email: '',
firstName: '',
lastName: '',
birthday: '',
verified: false,
};
#Action({commit: 'SET_USER'})
public async login(data: LoginEmailPost) {
try {
const resp = await Api.authenticationApi.v1LoginEmailPost(data);
Auth.injectAccessJWT(resp.data.tokenAccess.value);
Auth.injectRenewalJWT(resp.data.tokenRenewal.value);
return resp.data.user;
} catch (e) {
return e.statusCode;
}
}
#Mutation
public SET_USER(user: User) {
this.authenticated = true;
this.user = {...this.user, ...user};
}
}
export const AuthenticationModule = getModule(Authentication);
I took this setup from: https://github.com/calvin008/vue3-admin
I don't know if this is a bug or if this is a setup issue but completely stuck here as I intend to use the vuex-persist here to "rehydrate" the store after page reload.
Another completely different way of declaring the stores with this lib was here: https://github.com/eladcandroid/typescript-vuex-example/blob/master/src/components/Profile.vue but the syntax seems it would get wildly verbose when in the vue3-admin it is alll neatly in the store opposed to the component.
Currently I have all the state nicely persisted to local storage but I have no idea due to this error or and lack of exmaple how rehydrate the store with this stored data :/
It seems there are two ways to use the decorators but both are quite different. I like the method i have found from the vie admin as the components are nice and clean, but i cannot inject the modules as https://www.npmjs.com/package/vuex-persist#detailed states should be done :/

I found the answer to be the example vue admin app was not structured quite correctly.
Instead to export the class from the module:
#Module({ name: 'authentication' })
export default class Authentication extends VuexModule implements IAuthenticationState {
Then inject the class as a module into the index and export the module via the decorator but also inject the store into the said decorator:
import Vue from 'vue';
import Vuex from 'vuex';
import Authentication from './modules/authentication';
import VuexPersistence from 'vuex-persist';
import { getModule } from 'vuex-module-decorators';
Vue.use(Vuex);
const vuexLocal = new VuexPersistence({
storage: window.localStorage,
});
const store = new Vuex.Store({
modules: {
authentication: Authentication,
},
plugins: [vuexLocal.plugin],
});
export default store;
export const AuthenticationModule = getModule(Authentication, store);
The result is it all works.

Related

Migrating apollo-server-express to #apollo/server or graphql-yoga

apollo-server-express and apollo-server-cloud-functions are deprecated, which most tutorials online showing how to set up firebase CF with graphql rely on. I'm hoping someone can help me (and surely others), migrate things so they work with #apollo/server v4, or alternatively using another open source library, such as graphql-yoga.
To begin, here is how I had my server set up until recently:
import { ApolloServer } from "apollo-server-express";
import admin from "firebase-admin";
import express from "express";
import schema from "./schema";
import resolvers from "./resolvers";
import UsersAPI from "./datasources/users";
const serviceAccount = require("../../private/serviceAccount.json");
const databaseURL = "https://my-app.firebaseio.com";
const globalServerApp = admin.initializeApp(
{ credential: admin.credential.cert(serviceAccount), databaseURL },
"server"
);
const globalDataSources = {
usersAPI: new UsersAPI(globalServerApp)
};
const initServer = () => {
const app = express();
const server = new ApolloServer({
typeDefs: schema,
resolvers,
dataSources: () => {
return globalDataSources;
},
uploads: false,
introspection: true,
playground: true,
context: async ({ req }) => {
return {
request: req,
};
},
});
server.applyMiddleware({ app, path: "/", cors: true });
return app;
};
export default initServer;
In addition, I would have this for the users schema:
import { gql } from "apollo-server-express";
const UserSchema = gql`
scalar JSONObject
type Something {
customer: String
}
extend type Query {
doSomething(someIDs: [String]): [Something]
}
extend type Mutation {
completeRegistration(
uid: ID!
first_name: String
last_name: String
invited_by: JSONObject
): Boolean
}
`;
export default UserSchema;
How would you write these using #apollo/server v4, graphql-yoga or maybe another simple way?
The primary differences between the version of apollo-server-express you're using and #apollo/server v4 are:
Package name changes, obviously.
Server implementations have been removed. This was done so that implementations could be community-owned, rather than them having to learn each new thing. Lucky for you express middleware is still in the main package, but now you can use the expressMiddleware wrapper function instead of applyMiddleware.
Playground was deprecated and removed in favor of Apollo's own "Apollo Sandbox". If you prefer GraphQL Playground, there's a plugin that needs to be installed called #apollo/server-plugin-landing-page-graphql-playground. The code below assumes you've installed that.
context became an implementation-specific function, so is no longer on the ApolloServer config. It's now on the expressMiddleware function.
DataSources are no longer in the root config. The return of the context function should now include dataSources if you want them. This should generally be a bit more straightforward.
With all of that put together (though, admittedly, without me having your code, so I can't actually test this thing running), this is what I would expect to work for you:
// These are the new packages
import { ApolloServer } from '#apollo/server';
import { expressMiddleware } from '#apollo/server/express4';
import { ApolloServerPluginLandingPageGraphQLPlayground } from '#apollo/server-plugin-landing-page-graphql-playground';
import admin from 'firebase-admin';
import express from 'express';
import schema from './schema';
import resolvers from './resolvers';
import UsersAPI from './datasources/users';
const serviceAccount = require('../../private/serviceAccount.json');
const databaseURL = 'https://my-app.firebaseio.com';
const globalServerApp = admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL }, 'server');
const globalDataSources = {
usersAPI: new UsersAPI(globalServerApp),
};
const initServer = () => {
const app = express();
const server = new ApolloServer({
typeDefs: schema,
resolvers,
introspection: true,
plugins: [ApolloServerPluginLandingPageGraphQLPlayground()],
});
app.use(
'/',
expressMiddleware(server, {
context: async ({ req }) => {
return {
request: req,
dataSources: globalDataSources,
};
},
}),
);
return app;
};
export default initServer;

how to configure the effect reconciler to pass errors to rollback with redux-offline?

Problem
I have just recently found out about this library and was implementing it for a react native app, but can't get my head around how the effect reconciler passes the errors to rollback. I am firing the below action, and whether the response is success or failure, the effect reconciler directly passes everything to commit. can anyone tell me what I am doing wrong here?
const saveProfileRequest = (query, link): Action => ({
type: SAVE_PROFILE_PICTURE_REQUEST,
meta: {
offline: {
effect: {
url: BASE_URL,
method: 'POST',
body: JSON.stringify({
query,
variables: { url: link }
})
},
commit: { type: SAVE_PROFILE_PICTURE_SUCCESS, meta: { link } },
rollback: { type: SAVE_PROFILE_PICTURE_FAILURE }
}
}
});
Expectations
As I am currently implementing the offline capabilities to an existing app, I was expecting the effect reconciler to pass success response to commit and pass error response to rollback.
Store config
// #flow
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import { offline } from '#redux-offline/redux-offline';
import offlineConfig from '#redux-offline/redux-offline/lib/defaults';
import { persistStore, persistReducer } from 'redux-persist';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';
import thunkMiddleware from 'redux-thunk';
import AsyncStorage from '#react-native-community/async-storage';
import type { Store } from '#types/Store';
import rootReducer from '#reducers/index';
const persistConfig = {
key: 'root',
storage: AsyncStorage,
whitelist: ['reducerOne', 'reducerTwo', 'reducerThree'],
stateReconciler: autoMergeLevel2
};
const persistedReducer = persistReducer(
persistConfig,
combineReducers(rootReducer)
);
const store: Store = createStore(
persistedReducer,
composeWithDevTools(
applyMiddleware(thunkMiddleware),
offline({
...offlineConfig,
retry(_action, retries) {
return (retries + 1) * 1000;
},
returnPromises: true
})
)
);
I was having the same issue, because our GraphQL API always return 200, but with an error object, so I needed to customize it.
Basically you need to customize the discard function, returning false in case of an error.
The default discard already return false in case of Network issue, but if you have errors inside your response, and it's returning 200 instead, you can customize.
Documentation for Discard: https://github.com/redux-offline/redux-offline/blob/develop/docs/api/config.md#discard
Default implementation (you can use that as initial draft): https://github.com/redux-offline/redux-offline/blob/develop/src/defaults/discard.js

firebase.auth.GoogleAuthProvider is not a constructor

I'm trying to use google sign using firebase in the Vue framework. I don't know what the error is this can anyone help me with this.
vue.runtime.esm.js?2b0e:1888 TypeError: _firebase_js__WEBPACK_IMPORTED_MODULE_2__.fb.auth.GoogleAuthProvider is not a constructor
at VueComponent.socialLogin (Signin.vue?3d55:76)
at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:1854)
at HTMLButtonElement.invoker (vue.runtime.esm.js?2b0e:2179)
at HTMLButtonElement.original._wrapper (vue.runtime.esm.js?2b0e:6917)
this is my code
firebase.js
import firebase from "firebase";
var firebaseConfig = {
config
};
const fb=firebase.initializeApp(firebaseConfig);
export { fb };
Sign in.vue
<script>
import { fb } from "../firebase.js";
export default {
name: "Signin",
components: {},
data() {
return {
};
},
methods: {
socialLogin() {
const provider = new fb.auth.GoogleAuthProvider();
fb.auth().signInWithPopup(provider).then((result) => {
this.$router.replace('home');
}).catch((err) => {
alert('Oops. ' + err.message)
});
}
}
};
</script>
The auth property (not the auth() function) is available on the static firebase object, not your firebase app.
You want something more like this
import firebase from "firebase/app"
import "firebase/auth" // 👈 this could also be in your `firebase.js` file
const provider = new firebase.auth.GoogleAuthProvider()

React Redux Firebase: Error on firebaseConnect - Cannot read property 'ordered' of undefined

I followed the example in the documentation under v2.0.0 > Read Me > Load Data (listeners automatically managed on mount/unmount) (direct link is not possible).
And replaced the connect call with the firestore specific one shown here](http://react-redux-firebase.com/docs/firestore.html#examples) in Example 1.
I copied the Todo example exactly in a new component created for testing purposes.
Todo Component:
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { compose } from 'redux'
import { firebaseConnect,firestoreConnect, isLoaded, isEmpty } from 'react-redux-firebase'
const Todos = ({ todos, firebase }) => {
// Build Todos list if todos exist and are loaded
const todosList = !isLoaded(todos)
? 'Loading'
: isEmpty(todos)
? 'Todo list is empty'
: Object.keys(todos).map(
(key, id) => (
<TodoItem key={key} id={id} todo={todos[key]}/>
)
)
return (
<div>
<h1>Todos</h1>
<ul>
{todosList}
</ul>
<input type="text" ref="newTodo" />
<button onClick={this.handleAdd}>
Add
</button>
</div>
)
}
// export default compose(
// firestoreConnect([
// 'todos' // { path: '/todos' } // object notation
// ]),
// connect((state) => ({
// todos: state.firestore.data.todos,
// profile: state.firestore.profile // load profile
// }))
// )(Todos)
export default compose(
firestoreConnect(['todos']), // or { collection: 'todos' }
connect((state, props) => ({
todos: state.firestore.ordered.todos
}))
)(Todos)
The store configuration was configured as shown here in the docs. The store configuration was adapted to slot into the framework created by react-boilerplate.
/**
* Create the store with dynamic reducers
*/
import { createStore, applyMiddleware, compose } from 'redux'
import { fromJS } from 'immutable'
import { routerMiddleware } from 'connected-react-router/immutable'
import createSagaMiddleware from 'redux-saga'
import { reactReduxFirebase, firebaseReducer } from 'react-redux-firebase'
import { reduxFirestore, firestoreReducer } from 'redux-firestore'
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/database'
import 'firebase/firestore'
import createReducer from './reducers'
const sagaMiddleware = createSagaMiddleware()
const firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
}
const rrfConfig = {
userProfile: 'users',
// useFirestoreForProfile: true, // Firestore for Profile instead of Realtime DB
// attachAuthIsReady: true
}
// Initialize Cloud Firestore through Firebase
export default function configureStore(initialState = {}, history) {
firebase.initializeApp(firebaseConfig)
// Initialize Firestore with timeshot settings
firebase.firestore()
// firebase.firestore().settings({ timestampsInSnapshots: true })
// Create the store with two middlewares
// 1. sagaMiddleware: Makes redux-sagas work
// 2. routerMiddleware: Syncs the location/URL path to the state
const middlewares = [sagaMiddleware, routerMiddleware(history)]
const enhancers = [
applyMiddleware(...middlewares),
// reactReduxFirebase(config), // enhancing our store with these packages
// reduxFirestore(config)
]
// If Redux DevTools Extension is installed use it, otherwise use Redux compose
/* eslint-disable no-underscore-dangle, indent */
const composeEnhancers =
process.env.NODE_ENV !== 'production' &&
typeof window === 'object' &&
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
: compose
/* eslint-enable */
const createStoreWithFirebase = compose(
reactReduxFirebase(firebase, rrfConfig), // firebase instance as first argument
reduxFirestore(firebase),
)(createStore)
const store = createStoreWithFirebase(
createReducer(),
fromJS(initialState),
composeEnhancers(...enhancers),
)
// Extensions
store.runSaga = sagaMiddleware.run
store.injectedReducers = {} // Reducer registry
store.injectedSagas = {} // Saga registry
// Make reducers hot reloadable, see http://mxs.is/googmo
/* istanbul ignore next */
if (module.hot) {
module.hot.accept('./reducers', () => {
store.replaceReducer(createReducer(store.injectedReducers))
})
}
return store
}
I traced and verified my store configuration exactly to make sure all steps present in the documentation are configured correctly in my configuration.
My createReducer funciton is in a seperate file and you can see that I added the firebaseReducer and firebaseReducer correctly.
import { combineReducers } from 'redux-immutable'
import { connectRouter } from 'connected-react-router/immutable'
import { firebaseReducer } from 'react-redux-firebase'
import { firestoreReducer } from 'redux-firestore'
import history from 'utils/history'
import languageProviderReducer from 'containers/LanguageProvider/reducer'
export default function createReducer(injectedReducers = {}) {
const rootReducer = combineReducers({
firebase: firebaseReducer,
firestore: firestoreReducer,
language: languageProviderReducer,
...injectedReducers,
})
// Wrap the root reducer and return a new root reducer with router state
const mergeWithRouterState = connectRouter(history)
return mergeWithRouterState(rootReducer)
}
My redux store contains the firestore and firebase and it is injected into the component props.
What does not work is the use of connectFirestore HoC to automatically retrieve and inject a list of documents in to the component.
This is the error message:
react-dom.development.js?61bb:20266 Uncaught TypeError: Cannot read property 'ordered' of undefined
at Function.eval [as mapToProps] (index.js?d834:49)
at mapToPropsProxy (wrapMapToProps.js?1817:54)
at Function.detectFactoryAndVerify (wrapMapToProps.js?1817:63)
at mapToPropsProxy (wrapMapToProps.js?1817:54)
at handleFirstCall (selectorFactory.js?805c:37)
at pureFinalPropsSelector (selectorFactory.js?805c:85)
at Object.runComponentSelector [as run] (connectAdvanced.js?48b8:43)
at Connect.initSelector (connectAdvanced.js?48b8:195)
at new Connect (connectAdvanced.js?48b8:136)
at constructClassInstance (react-dom.development.js?61bb:11315)
(Snipped from my code which is the example 1 in documentation):
export default compose(
firestoreConnect(['todos']), // or { collection: 'todos' }
connect((state, props) => ({
todos: state.firestore.ordered.todos
}))
)(Todos)
I inspected the state variable and it does contain the firestore attribute. This attribute contains a number of functions, as expected, but it is missing the query results under "ordered", which is undefined.
I have tried all different ways to use firestoreconnect e.g. using a Class-based component, using a query with parameters, etc. and all give the same error.
My Firebase project is configured correct as I am able to create documents inside collections. A todos collection for testing purposes is present as well containing 2 documents.
I have come across this post, which mentions the following:
If you just upgraded to React-Redux v6, it's because react-redux-firebase is not compatible with v6.
See https://github.com/prescottprue/react-redux-firebase/issues/581 for details.
This does not apply to me because I am using react-redux version 5. Here are the versions I am using:
"firebase": "^5.10.1",
"react-redux": "^5.0.7",
"react-redux-firebase": "^2.2.6",
"redux": "^4.0.1",
"redux-firestore": "^0.7.3",
I have spent a significant amount of time on this. Like I said, using firestore to add new data to collections works fine. It is just this HoC business that is failing no matter how i approach the solution.
any help would be appreciated.
Never solved this. I guess it is related to incompatible versions. What I ended up doing is download v4 of react-boilerplate and set up v3 react-redux-firebase which uses the Context API as opposed to store enhancers. Now works very well.

Trying to add multiple reducers to a forFeature lazy loading module 'ids' of undefined at selectIds'

I am trying to implement ngrx on an app but having this problem of connecting the states. I have a root reducer that provides to store as StoreModule.forRoot(reducers) in the app.module.ts
rootreducer:
import * as fromAuth from 'app/auth/auth.reducer'
import { authReducer } from 'app/auth/auth.reducer';
export interface State {
auth: fromAuth.State;
}
export const reducers: ActionReducerMap<State> = {
auth: fromAuth.authReducer
};
I created an index.ts in the lazyloading folder lazyloading/index.ts:
export interface CollectionsState {
collections: fromCollections.State;
pages: fromPages.State;
}
export interface State extends fromRoot.State {
collections: CollectionsState;
}
export const reducers = {
collection: fromCollections.collectionReducer,
page: fromPages.pageReducer
};
export const getCollectionsState = createFeatureSelector<CollectionsState>('collections');
export const getCollectionEntitiesState = createSelector(
getCollectionsState,
state => state.collections
);
And in the lazy loaded module provided it as StoreModule.forFeature('collections', reducers)
Then I try to use it in a component as
import { Store, select } from '#ngrx/store';
import * as actions from '#collections/state/actions/collection.actions';
import * as fromCollections from '#collections/state';
//get collections
this.cols = this.store.pipe(select(fromCollections.selectAll))
this.store.dispatch( new actions.Query() );
This gives me an error, undefined at selectIds
IndexComponent.html:10 ERROR TypeError: Cannot read property 'ids' of
undefined at selectIds (entity.es5.js:45) at eval (store.es5.js:567)
at Array.map ()
......
How can I fix this?

Resources