overload Array parameter - javascript

i'm Python'ist and i hate ugly js
here is solution to make it usable for me
import { createApp } from 'vue'
import App from './App.vue'
var array_len_plugin = {
install()
{
Array.prototype.len = function () { return this.length }
}
}
var app = createApp( App )
app.use( array_len_plugin )
app.mount( '#app' )
but it's obviously work not as default one
Array.prototype.len = Array.prototype.length
how to make this work?

Object.defineProperty( Array.prototype, "len", { get() { return this.length } } )

Related

let or React.useRef: what is the best approach?

I'm developing a REACT JS app and I've a doubt. If I have something that must not be taken as a dependency i usually put a let like in this case, where I'm initializing Firebase for my app:
import { initializeApp } from 'firebase/app';
import { initializeAppCheck, ReCaptchaV3Provider } from 'firebase/app-check';
let app = null;
const useInitializeFirebase = () => {
if (app) {
return;
}
app = initializeApp(window.FIREBASE);
initializeAppCheck(app, {
provider: new ReCaptchaV3Provider(window.RECAPTCHA_SITE_KEY),
isTokenAutoRefreshEnabled: true,
});
};
export default useInitializeFirebase;
The so exported hook is called within the main index.js file in this way:
const App = () => {
useInitializeFirebase();
...
}
So if the hook gets called multiple times (e.g. for a re-render), Firebase won't give error.
Is this the best approach? Or maybe I should use useRef or useState or even something else?
EDIT
The problem occurs also if I don't use an hook.
Take this code as reference:
import { initializeApp } from 'firebase/app';
let firebaseApp = null;
export default (firebaseConfig) => {
if (firebaseApp === null) {
firebaseApp = initializeApp(firebaseConfig);
}
return firebaseApp;
};
That can be used in this way
import { getAuth, signInWithCustomToken } from 'firebase/auth';
import firebaseApp from '#Src/helpers/firebaseApp';
const firebaseLogin = (token) => {
const auth = getAuth(firebaseApp(window.FIREBASE));
return signInWithCustomToken(auth, token);
};
export { firebaseLogin };
In this way if I don't put a guard firebase would be initialized multiple times, giving error.

Undefined functions when using mobx store with class instance as property

I am using mobx and decimal.js.
This is my store:
import Decimal from "decimal.js";
import { makeObservable, observable, action } from "mobx";
class MyStore {
public value: Decimal | null = null;
constructor() {
makeObservable(this, {
value: observable,
setValue: action,
});
}
public setValue() {
this.value = new Decimal(100);
}
}
export { MyStore };
This is my component:
import { useStoreValue } from "../../state/StoreContext";
import { observer } from "mobx-react-lite";
const MyPage = observer(() => {
const value = useStoreValue((rootStore) => rootStore.myStore.value);
return <span>{value.mul(5)}</span>;
});
export { MyPage };
As a result I get the following exception:
useObserver.ts:119 Uncaught TypeError: _value.mul is not a function
Any idea what I am missing?

Using `useStore` API with vuex 4.x

Follow the official example to export your own useStore, and then use it in the component.
import { createStore, Store, useStore as baseUseStore } from 'vuex';
export const key: InjectionKey<Store<RootState>> = Symbol();
export function useStore() {
return baseUseStore(key);
}
use in the component
setup() {
const store = useStore();
const onClick = () => {
console.log(store)
store.dispatch('user/getUserInfo');
}
return {
onClick,
}
},
After running, store is undefined.
It can be obtained normally when I use it in the methods attribute
methods: {
login() {
this.$store.dispatch('user/getToken')
}
}
why? how to fix it
In that simplifying useStore usage tutorial, you still need to register the store and key in main.ts as they did. You will get undefined if you don't do this:
// main.ts
import { store, key } from './store'
const app = createApp({ ... })
// pass the injection key
app.use(store, key)
The reason is that baseUseStore(key) has no meaning until that's done.

How to change module.exports to import and export?

module.exports = function (idx) {
this.camera = idx;
};
module.exports.CONFIG = function () {
return Promise.resolve([]);
};
module.exports.CONFIG.FLOOR = function () {
return Promise.resolve([]);
}
I have a file that contains code like above.
I require this file and console.log it. It only shows
function (idx) {
this.camera = idx;
}
Why other attributes are hidden?
And if I delete first module.exports paragraph and console.log it, it shows an anonymous function(or default function ?) in CONFIG.
{ CONFIG:
{ [Function]
FLOOR: [FUNCTION]
}
}
I am wondering how to change it to import/export type instead of module.exports/require?
Thanks!
It looks like you have both named exports and a default export. When exporting, that would look something like:
// Default export:
export default function (idx) {
this.camera = idx;
};
function CONFIG() {
return Promise.resolve([]);
}
CONFIG.FLOOR = function () {
return Promise.resolve([]);
}
// Named export:
export CONFIG;
Then, when importing them, you need to both import the default and the named:
import idxFn, { CONFIG } from '../foo';
^^^^^ default import
^^^^^^ named import
You'll then be able to access FLOOR by referencing CONFIG.FLOOR.
But, note that having a function which is a property of another function is really weird. You might consider exporting FLOOR as another named export instead, just like CONFIG:
// Default export:
export default function (idx) {
this.camera = idx;
};
// Named exports:
export function CONFIG() {
return Promise.resolve([]);
}
export function FLOOR () {
return Promise.resolve([]);
}

React with Flux: is this the dogmatic pattern or are there equal/better options?

I've recently learned how to code in React and how to structure the code using Flux. Unfortunately Firebase doesn't play to well with Flux and I need to set up a quick and easy back-end up for a prototype. Some suggest to forgo Flux altogether and to just use Firebase but I'm not sure if Flux will be almost necessary down the road when I hook up a real backend. If it is necessary, should I just force fit React into flux for now and unplug it later, or are there better alternatives to Flux out that I should be taking advantage of? Forgive the noob nature of this question. :)
Here is the basic reflux pattern I use starting with app.js;
import React from 'react';
import AppCtrl from './components/app.ctrl.js';
import Actions from './flux/Actions';
import ApiStore from './flux/Api.Store';
window.React = React;
Actions.apiInit();
React.render( <AppCtrl />, document.getElementById('react') );
app.ctrl.js
import React, {Component} from 'react';
import BasicStore from './../flux/Basic.Store';
var AppCtrlSty = {
height: '100%',
padding: '0 10px 0 0'
}
class AppCtrlRender extends Component {
binder(...methods) { methods.forEach( (method) => this[method] = this[method].bind(this) ); }
render() {
var data = this.state.Data;
data = JSON.stringify(data, null, 2);
var data2 = this.state.Data2;
data2 = JSON.stringify(data2, null, 2);
var data3 = this.state.Data3;
data3 = JSON.stringify(data3, null, 2);
return (
<div id='AppCtrlSty' style={AppCtrlSty}>
React 1.3 ReFlux with WebSocket<br/><br/>
{data}<br/><br/>
Data2: {data2}<br/><br/>
Data3: {data3}<br/><br/>
</div>
);
}
}
function getState() {
return {
Data: BasicStore.getData(),
Data2: BasicStore.getData2(),
Data3: BasicStore.getData3()
};
};
export default class AppCtrl extends AppCtrlRender {
constructor() {
super();
this.state = getState();
this.binder('storeDidChange');
}
componentDidMount() { this.unsubscribe = BasicStore.listen(this.storeDidChange); }
componentWillUnmount() { this.unsubscribe(); }
storeDidChange() { this.setState(getState()); }
}
Actions.js
import Reflux from 'reflux';
var apiActions = [
'apiInit',
'apiInitDone',
'apiSetData'
]
var wsActions = [
'gotData',
'gotData2'
]
var actionArray = wsActions.concat(apiActions);
module.exports = Reflux.createActions(actionArray);
Api.Store.js
import Reflux from 'reflux';
import Actions from './Actions';
import ApiFct from './../utils/ws.api.js';
function _apiInit() { ApiFct.init(); }
function _apiInitDone() { ApiFct.getData(); }
function _apiSetData(data) { ApiFct.setData(data); }
var ApiStoreObject = {
listenables: Actions,
apiInit: _apiInit,
apiInitDone: _apiInitDone,
apiSetData: _apiSetData
}
const ApiStore = Reflux.createStore(ApiStoreObject);
export default ApiStore;
ws.api.js. This is where you talk to firebase on the server. When you get data from the server just trigger the action to send the data to the store.
import Actions from '../flux/Actions';
module.exports = {
socket: {},
init: function() {
this.socket = new Primus();
this.socket.on('server:GotData', this.gotData);
Actions.apiInitDone();
},
getData: function() { this.socket.send('client:GetData', {}); },
gotData: function(data) { Actions.gotData(data); Actions.gotData2(data); },
setData: function(data) { this.socket.send('client:SetData', data); },
};
Basic.Store.js
import Reflux from 'reflux';
import Actions from './Actions';
import AddonStore from './Addon.Store';
import MixinStoreObject from './Mixin.Store';
var _data = {};
function _gotData(data) { _data = data; BasicStore.trigger(); }
function _addonTrigger() { BasicStore.trigger(); }
function BasicStoreInit() { this.listenTo(AddonStore, this.onAddonTrigger); }
var BasicStoreObject = {
init: BasicStoreInit,
listenables: Actions,
mixins: [MixinStoreObject],
onGotData: _gotData,
onAddonTrigger: _addonTrigger,
getData: function() { return _data; },
getData2: function() { return AddonStore.data2; },
getData3: function() { return this.data3; }
}
const BasicStore = Reflux.createStore(BasicStoreObject);
export default BasicStore;
The complete pattern is at https://github.com/calitek/ReactPatterns under React.13/ReFluxWebSocket.

Categories

Resources