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

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.

Related

React / Redux - Error: Actions must be plain objects. Use custom middleware for async actions

I am getting this error even though I am using redux thunk. Redux store is also set up correctly (I think). I am creating a MERN app and I want to send a POST request to the backend (form submit) to create a new user. The request and response from the server are fine (checked using Postman). I just can not find where the problem is. The action creator which is causing this is :-
import axios from "axios";
export function signupUser(newuser) {
return function (dispatch) {
axios.post("/auth", newuser).then((res) => {
// dispatch
dispatch({
type: "ADDNEW_USER",
payload: res.data,
});
});
};
}
The store setup is :-
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducers";
const initialState = {};
// const middleware = [thunk];
const store = createStore(
rootReducer,
initialState,
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
The Signup.js component is ->
[Signup.js][1]
and the error is -> [here][2]
[1]: https://paste.ubuntu.com/p/gCX3wQPt9X/
[2]: https://imgur.com/a/6SDmydw

Vuex and API calls

I'm trying to implement Vuex in an app I'm building to learn more about Vue.js. The idea is pretty simple: retrieving user information and a list of items (everything is stored on Firebase).
I get the idea of Vuex, but the tutorials I can find only rely on data stored locally in the store. I can't get my head around how it would work when the data in the store has to be kept in sync with an external database.
Did I totally miss something? or maybe is Vuex not the best solution for that?
If you want "the data in the (Vue.js) store to be kept in sync with an external (Firestore) database", you could do as follows, taking advantage of the onSnapshot() method which "attaches a listener for QuerySnapshot events".
Let's imagine you have a cities collection in your Firestore database, and each document of this collection has a field name, which holds the city name.
First, declare the Firebase config in a firebaseConfig.js file:
firebaseConfig.js
import firebase from 'firebase/app';
import 'firebase/firestore';
// firebase init goes here
const config = {
apiKey: 'xxxxxxxxxxxxxxxxxx',
authDomain: 'xxxxxxxxx.firebaseapp.com',
databaseURL: 'xxxxxxxxxxxxxxxxxx',
projectId: 'xxxxxxxxxxxxxxxxxx'
};
firebase.initializeApp(config);
const db = firebase.firestore();
export { db };
Then set-up your Vuex store as follows:
store.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
cities: []
},
mutations: {
SET_CITIES(state, val) {
state.cities = val;
}
},
actions: {
//You may add here an action that would commit the SET_CITIES mutation
}
});
Then, modify the main.js file as follows:
main.js
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
const fb = require('./firebaseConfig.js');
Vue.config.productionTip = false;
new Vue({
router,
store,
beforeCreate() {
fb.db.collection('cities').onSnapshot(querySnapshot => {
var c = [];
querySnapshot.forEach(doc => {
c.push({
id: doc.id,
name: doc.data().name
});
});
store.commit('SET_CITIES', c);
});
},
render: h => h(App)
}).$mount('#app');
You are all set! Just try getting the cities array in a Component, as follows:
HelloWorld.vue
<template>
<div>
<ul>
<li v-for="c in cities" v-bind:key="c.id">{{ c.name }}</li>
</ul>
</div>
</template>
<script>
import { mapState } from "vuex";
export default {
name: "HelloWorld",
computed: {
...mapState(["cities"])
}
};
</script>
and try adding, removing or modifying records in the database.

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?

Redux, Firebase, and react-native: fetch data async

I'm developing a React-native app, using Redux and Firebase.
My Firebase database is denormalized, so it looks like:
users:
user_uid:
my_posts: [ post_key1, post_key2 ]
posts
post_key1: { post_details }
post_key2: { post_details }
How should I fetch data asynchronously and dispatch posts data to Redux store?
I know about Firebase methods .on('value') and .once('value'), but I'm not able to write a proper async function/thunk without generating issues.
If you are using react-redux-firebase to integrate redux with Firebase, the v2.0.0 docs show using react-native with examples for using either native-modules through react-native-firebase or the JS SDK.
With the structure you have shown, it may also be helpful for you to use populate to easily load posts automatically when loading users.
If you have the users uid on the post object under owner, you could do something like:
Home.js
import { compose } from 'redux'
import { connect } from 'react-redux'
import { firebaseConnect, populate } from 'react-redux-firebase'
const populates = [
{ child: 'owner', root: 'users' } // replace owner with user object
]
const enhance = compose(
firebaseConnect([
// passing populates parameter also creates all necessary child queries
{ path: 'posts', populates }
]),
connect(({ firebase }) => ({
// populate original from data within separate paths redux
posts: populate(firebase, 'posts', populates),
}))
)
const SomeComponent = ({ posts }) => <div>{JSON.stringify(posts, null, 2)}</div>
export default enhance(SomeComponent)
App.js
import { createStore, combineReducers, compose } from 'redux'
import { connect } from 'react-redux'
import { reactReduxFirebase, firebaseReducer } from 'react-redux-firebase'
import firebase from 'firebase'
import Home from './Home' // code above
const firebaseConfig = {} // config from firebase console
// react-redux-firebase config
const rrfConfig = {
userProfile: 'users' // automatically manage profile
}
// initialize firebase instance
firebase.initializeApp(config) // <- new to v2.*.*
// Add reduxReduxFirebase enhancer when making store creator
const createStoreWithFirebase = compose(
reactReduxFirebase(firebase, rrfConfig)
)(createStore)
// Add Firebase to reducers
const rootReducer = combineReducers({
firebase: firebaseStateReducer
})
// Create store with reducers and initial state
const initialState = {}
const store = createStoreWithFirebase(rootReducer, initialState)
const App = () => (
<Provider store={store}>
<Home />
</Provider>
);
ReactDOM.render(<App/>, document.querySelector('#app'));

update redux reducers after store initialization

I am new to redux architecture, I have this basic doubt can we update the reducers list after creating the store using combinedReducer and createStore methods?
Yes, you can update the reducers and inject a new one asynchronously with replaceReducer api of Redux store.
It is an advanced API. You might need this if your app implements code
splitting, and you want to load some of the reducers dynamically. You
might also need this if you implement a hot reloading mechanism for
Redux.
Take as example this starter-kit
In createStore.js file the reducers passed as arguments to the createStore method are the result of makeRootReducers(). Pay attention to the fact that no one async reducer have been passed to this function.
// extract of src/store/createStore.js
import { applyMiddleware, compose, createStore } from 'redux'
import { routerMiddleware } from 'react-router-redux'
import thunk from 'redux-thunk'
import makeRootReducer from './reducers'
export default (initialState = {}, history) => {
// ...
// ======================================================
// Store Instantiation and HMR Setup
// ======================================================
const store = createStore(
makeRootReducer(), // <------------- without arguments, it returns only the synchronously reducers
initialState,
compose(
applyMiddleware(...middleware),
...enhancers
)
)
store.asyncReducers = {}
// ...
}
In reducers.js file:
makeRootReducer function calls combineReducers with the default reducers
needed for the startup (like router reducer) and other "asynchronously" reducers passed as arguments
injectReducer is a function called for injecting new reducers on runtime. It call replaceReducer api on the store passing as argument a new list of reducers obtain through makeRootReducer(async) function
see below:
// src/store/reducers.js
import { combineReducers } from 'redux'
import { routerReducer as router } from 'react-router-redux'
export const makeRootReducer = (asyncReducers) => {
return combineReducers({
// Add sync reducers here
router,
...asyncReducers
})
}
export const injectReducer = (store, { key, reducer }) => {
store.asyncReducers[key] = reducer
store.replaceReducer(makeRootReducer(store.asyncReducers))
}
export default makeRootReducer
Finally, in the starter-kit the reducer is injected on route definition, like here:
// src/routes/Counter/index.js
import { injectReducer } from '../../store/reducers'
export default (store) => ({
path: 'counter',
/* Async getComponent is only invoked when route matches */
getComponent (nextState, cb) {
/* Webpack - use 'require.ensure' to create a split point
and embed an async module loader (jsonp) when bundling */
require.ensure([], (require) => {
/* Webpack - use require callback to define
dependencies for bundling */
const Counter = require('./containers/CounterContainer').default
const reducer = require('./modules/counter').default
/* ----> HERE <---- */
/* Add the reducer to the store on key 'counter' */
injectReducer(store, { key: 'counter', reducer }) // <-------
/* Return getComponent */
cb(null, Counter)
/* Webpack named bundle */
}, 'counter')
}
This technique is helpful when you want split a large app and avoid to load all the reducers at the boot.

Resources