ES6 Import multiple files and extend main object - ecmascript-6

i would like to extend A in main.js using multiple import files, example
// main.js
A = {
a : 0
};
import './b.js'
import './c.js'
...
export default A;
// b.js
import A from './main.js'
A.b = 1;
// c.js
import A from './main.js'
A.c = 2;
// App.js
import A from './main.js'
console.log(A);
what i get in console.log(A) is { a : 0 }
how to extend A in main.js and while import to App.js, A will be extended to
A = {
a : 0,
b : 1,
c : 2
}

When you create a module, module.exports automatically is initialized to an empty object {}. So when you do something like module.exports = A, what you're doing is to replace this default object with your object A.
What is happening in your code, is that you're defining A but you're not exporting it yet, so what b.js and c.js receives from the import of main.js is not A, but the default module.exports object, and is the one that they are modifying.
So you have 2 options to modify main.js so it works. The first one is to export A before main.js is imported by other modules:
// main.js
A = {};
export default A;
import './b.js'
import './c.js'
...
The other option, is to not have A at all and work directly with the default object returned by module.exports
// main.js
import './b.js'
import './c.js'
...

Related

react-redux-firebase firestore returns function and not object

I'm trying to use firestore with react-redux-firebase on a React App, and when I try to access state.firestore it returns a function and no the object. I'll attach the code for initialization.
This is the app file.
import React from "react";
import ReactDOM from "react-dom";
import "./index.styles.ts";
import * as serviceWorker from "./serviceWorker";
import Theme from "./components/Theme";
import configureStore from "./store/configureStore";
import { Provider } from "react-redux";
import Routes from "routes";
import firebase from 'firebase/app'
import 'firebase/auth';
import 'firebase/firestore';
// import 'firebase/functions' // <- needed if using httpsCallable
import {
ReactReduxFirebaseProvider,
} from 'react-redux-firebase'
import { createFirestoreInstance } from 'redux-firestore';
const firebaseConfig = {
};
// react-redux-firebase config
const rrfConfig = {
userProfile: 'users',
useFirestoreForProfile: true // Firestore for Profile instead of Realtime DB
// enableClaims: true // Get custom claims along with the profile
}
// Initialize firebase instance
firebase.initializeApp(firebaseConfig);
firebase.firestore();
const store = configureStore();
const rrfProps = {
firebase,
config: rrfConfig,
dispatch: store.dispatch,
createFirestoreInstance
};
ReactDOM.render(
<Theme>
<Provider store={store}>
<ReactReduxFirebaseProvider {...rrfProps}>
<Routes />
</ReactReduxFirebaseProvider>
</Provider>
</Theme>,
document.getElementById("root")
);
serviceWorker.unregister();
According to the docs, this is basically what's needed to be able to access firestore.
This is the configureStore file
import { createBrowserHistory } from "history";
import { createStore, applyMiddleware, Store } from "redux";
import { routerMiddleware } from "connected-react-router";
import thunk from "redux-thunk";
import { History } from "history";
import { combineReducers, compose } from "redux";
import { connectRouter } from "connected-react-router";
import * as reducers from "./reducers";
import { firebaseReducer } from "react-redux-firebase";
import { reduxFirestore } from "redux-firestore";
export const history = createBrowserHistory();
const createRootReducer = (history: History<any>) =>
combineReducers({
router: connectRouter(history),
firebase: firebaseReducer,
firestore: reduxFirestore,
...reducers,
});
export default function configureStore(): Store {
const store = createStore(
createRootReducer(history), // root reducer with router state
compose(
applyMiddleware(
routerMiddleware(history), // for dispatching history actions
thunk
)
)
);
return store;
}
Update: As confirmed by #luis, the fix was actually importing firestoreReducer instead of reduxFirestore in the configureStore.ts.
You are setting fiterstore as reduxFirestore, which is imported from redux-firestore library which is indeed a function.
I am not sure if you are using it correctly. Following is usage code from library's npm page:
import { createStore, combineReducers, compose } from 'redux';
import { reduxFirestore, firestoreReducer } from 'redux-firestore';
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
import 'firebase/firestore';
const firebaseConfig = {}; // from Firebase Console
const rfConfig = {}; // optional redux-firestore Config Options
// Initialize firebase instance
firebase.initializeApp(firebaseConfig);
// Initialize Cloud Firestore through Firebase
firebase.firestore();
// Add reduxFirestore store enhancer to store creator
const createStoreWithFirebase = compose(
reduxFirestore(firebase, rfConfig), // firebase instance as first argument, rfConfig as optional second
)(createStore);
// Add Firebase to reducers
const rootReducer = combineReducers({
firestore: firestoreReducer,
});
// Create store with reducers and initial state
const initialState = {};
const store = createStoreWithFirebase(rootReducer, initialState);
Notice how createStoreWithFirebase is called instead of createStore and firestoreReducer is passed along with an initial state.

Unit Testing to see if JSON file is null

I am currently trying to unit test a container that pulls in a static JSON file of phone numbers and passes it to the component to display, however I am not sure how I should go about testing it. The code for the container is as follows:
import React from 'react';
import data from *JSON file location*
import CountryInfo from *component for the country information* ;
class CountryInfoContainer extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
numbersJson: null
};
}
async componentWillMount() {
const numbersJson = data;
this.setState({ numbersJson });
}
render() {
return (
<CountryInfo json={this.state.numbersJson} showText={this.props.showText} />
);
}
}
export default CountryInfoContainer;
I currently have my unit test to look like this
import React from 'react';
import Adapter from 'enzyme-adapter-react-16';
import { mount, configure } from 'enzyme';
import { MemoryRouter } from 'react-router-dom';
import CountryInfoContainer from './CountryInfoContainer';
configure({ adapter: new Adapter() });
describe('Successful flows', () => {
test('checks if json has null entries', () => {
const wrapper = mount(<MemoryRouter><CountryInfoContainer /></MemoryRouter >);
const data = wrapper.find(numbersJson);
// eslint-disable-next-line no-console
console.log(data.debug);
});
});
Obviously, it doesn't work now because I am not sure how to use the variable numbersJson in the container in the test file or how to check if it is null.
The variable numbersJson is not defined in the scope of your test. If I understand correctly, you are testing that when you first mount the component, that it's state contains a null value for the numbersJson key.
First of all, you need to mount your component directly without MemoryRouter:
const wrapper = mount(<CountryInfoContainer />);
Then you can write an expect() for the state:
expect(wrapper.state().numbersJson).toBeNull();

Mock namespace function (Mocha, sinon, es6)

I have a util module consisting of the following namespaced exports
// utils.js
export const getWindowLocation(){window.location}
export const func2(){getWindowLocation().href = ....}
I would like to stub/override getWindowLocation in my mocha test
//UtilTest.js
import * as utils from "src/js/utils/utils";
import sinon from "sinon";
describe("Utils", () => {
beforeEach(() => {
sinon.stub(utils, "getWindowLocation").returns({});
});
....
The stub seems not to be overriding my method. I am not sure if namespaced function should be treated differently?
Thank you,

access store outside of component vuejs

I have a file for configuring my OpenID Connect authentication
export const authMgr = new Oidc.UserManager({
userStore: new Oidc.WebStorageStateStore(),
authority: **appsetting.oidc**
})
I want to access my state in order to get the value of appsetting.
I did this:
import store from './store'
const appsetting = () => store.getters.appsetting
but my appsetting is always returning undefined
what I my missing?
Store:
app.js
const state = {
appsetting: appsetting,
}
export {
state
}
getters.js
const appsetting = state => state.appsetting
export {
appsetting
}
index.js
export default new Vuex.Store({
actions,
getters,
modules: {
app
},
strict: debug,
plugins: [createLogger]
})
when I print the value of store.getters, it returns this:
{
return __WEBPACK_IMPORTED_MODULE_2__store__["a" /* default */].getters;
}
No the actual store objects
Try to import 'store' with curly brackets
import {store} from '../store/index'
store.getters.appSettings
Another option is to access from the vue property
import Vue from 'vue'
Vue.store.getters.appSettings
As for 2023 accesing store with
import {store} from '../store/index'
store.getters.appSettings
wasnt working for me but after removing curly brackets like so:
import store from '../store/index'
store.getters.appSettings
It started working as intended

Problems to map a json with axios.get

My name is Jose and i'm trying to fetch data Json in an array to be displayed with react. My json file is:
[{"nid":"460","title":"Prueba local","parent":"null"},
{"nid":"458","title":"Otra prueba","parent":"null"}...
My js file is:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios'
import './index.css';
class Ramas extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount(){
axios
.get('../proceso.json')
.then(({ data })=> {
this.setState({
data
});
})
.catch((err)=> {console.log('no recibido')})
}
I do not get any results. I appreciate any help.
My folder structure:
react_root
-nodemodules
-public
--index.html
-src
--index.js
The json file is in vps.../fuentes/proceso.json. It's another server an i can access to it via url
Thank you
There is no need of axios for this,
The real use of axios is when you want to fetch data from API or out of your server , if proceso.js was on a different server then its good to use.
What you can do is create one file ;
// proceso.js
export default [
{"nid":"460","title":"Prueba local","parent":"null"},
{"nid":"458","title":"Otra prueba","parent":"null"}
...
]
Then use it like :
import proceso from 'path/to/proceso.js';
componentDidMount(){
this.setState({
data : proceso
});
}
If your json file is being updated by server then put the file inside public folder and then try to call axios via public folder path,
Because once the build is generated, you will not be able to access other directories, like src directory