Exporting function in ES6 / react - javascript

On the server side (nodejs/express), I have no problems in exporting and referencing this file (using Attempt1).
// collectionFile.js
function collection() {
let data = {};
function getData(key) {
return data[key];
}
function setData(key, value) {
data[key] = value;
}
return {
getData: getData,
setData: setData
};
}
const instanceOfCollection = collection();
On the client side (React), I'm just not able to reference and access the getData function. Below are some of the combination I tried. None of them work. How can I make it work ?
// Attempt1: export
// module.exports.getter = instanceOfCollection.getData;
// Attempt1: import
// const getter = require('./collectionFile').getter;
// Uncaught TypeError: getter is not a function
// Attempt2: export
// export default { instanceOfCollection };
// Attempt2: import
// import instanceOfCollection from './collectionFile';
// const instance = instanceOfCollection.getData;
// Uncaught TypeError: Cannot read property 'getData' of undefined
// Attempt3: export
// export const instanceOfCollection = collection();
// Attempt3: import
// import { instanceOfCollection } from './collectionFile';
// const instance = instanceOfCollection.getData;
// Uncaught TypeError: Cannot read property 'getData' of undefined
Edit: Turns out that I was referencing File A from File B and also File B from File A earlier

There are a lot of ways to do such things:
ES5 export
module.export = instanceOfCollection
then
var getData = require('my_module').getData
ES6 export
export default instanceOfCollection
then
import { getData, setData } from 'my_module'
ES6 named export
export const setter = instanceOfCollection.setData
export const getter = instanceOfCollection.getData
then
import { setter, getter } from 'my_module'
or
import * as myCollection from 'my_module'
myCollection.getter()
myCollection.setter()
ES5 with renaming
module.export = {
getter: instanceOfCollection.getData,
setter: instanceOfCollection.setData,
}
then
const { setter, getter } = require('my_module')
or
const getter = require('my_module').getter
const setter = require('my_module').setter
Hope some of them will work for you.

Related

Use exported value in setup of Vue Composition API

In a plain js file the code looks like
export default async function exportData() {
const { data } = await store
.dispatch('fetchData')
const { bookings } = data
const booking = bookings.length ? bookings[0]._id : ''
const event = {
bookingID: booking
}
// other methods and variables
return {
.....
}
}
inside the vue file
import exportData from './exportData'
export default {
setup() {
const {
fetchEvents,
isEventActive,
} = exportData()
fetchEvents()
}
}
the problem is in vue components the values from exportData gets undefined, gets error fetchEvents is not a function when the export is asynchronous. works well if not asynchronous. what is the workaround here??
You can try to declare fetchEvents,isEventActive methods in plan js file without wrapping it inside any function
const fetchEvents = () => {
//body
};
const isEventActive = () => {
//body
};
and export them as
export {fetchEvents, isEventActive};
now use them
import {fetchEvents,isEventActive} from 'path-to-js-file'
export default {
setup() {
fetchEvents()
isEventActive()
}
}

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.

jest.spyOn does not work for an imported function. Expected mock function to have been called, but it was not called

jest.spyOn does not work for an imported function.
There is an error - Expected mock function to have been called, but it was not called.
import testFn from 'test'
// test.js
// import foo from 'foo'
// export default () => foo('text')
import * as foo from 'foo'
// foo.js
// export default (value) => value
const spyFn = jest.spyOn(foo, 'default')
testFn()
expect(spyFn).toHaveBeenCalled()
I expect that the default function is mocked.
Found the solution.
import testFn from 'test'
...
it('ola', () => {
const foo = require('foo')
const spyFn = jest.spyOn(foo, 'default')
testFn()
expect(spyFn).toHaveBeenCalled()
})
...

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-native: Export function using 'this' from other component

I'm actually having an issue in my React-native logic and I need your precious help !
I have my main component 'Main.js' and I want to import a function from 'Function.js' that should change the state of 'Main.js'...
But of course I don't have access to "Main.js"'s this.
So my question is:
How can I change the Main.js state from an exported function in Function.js ?
Here is the kind of code in Function.js
_function = () => {
... Getting MyState in AsyncStorage ...
var MyState = ...;
this.setState({ User: MyState })
}
And my Main.js
import { _function } from 'Function.js'
...
componentDidMount(){
this._function()
}
...
Either make the instance a parameter of the function:
export const _function = (main) => {
// ... Getting MyState in AsyncStorage ...
var MyState = …
main.setState({ User: MyState })
};
import { _function } from 'Function.js'
…
componentDidMount(){
_function(this)
}
…
Or don't use an arrow function so that you can actually use it as a method:
export function _function() {
// ... Getting MyState in AsyncStorage ...
var MyState = …
this.setState({ User: MyState })
};
import { _function } from 'Function.js'
…
componentDidMount(){
_function.call(this)
}
…
You could even install it as a real method:
import { _function } from 'Function.js'
class Main {
componentDidMount(){
this.method();
}
}
Main.prototype.method = _function;
You can pass a function in your _function parameters.
In main.js, you would have a function
setUser = (User) => {
this.setState({user});
}
Then you call _function and pass setUser as a parameter.
componentDidMount(){
_function(this.setUser)
}
In Function.js, you edit your function to receive the function and call it.
_function = (setUser) => {
... Getting MyState in AsyncStorage ...
var MyState = ...;
setUser(MyState);
}

Categories

Resources