Exporting an Object directly? - javascript

I'm trying to export an object directly, but I'm not getting the results I'd like;
const cmd = {
name: "testFunc",
desc: "Test",
execute(name, args) {
console.log("Test ()");
}
}
export {cmd}
I import it as follows;
import(`./commands/${file}`).then(cmd => {
console.log(cmd.cmd.name);
})
But I would rather be able to just do cmd.name, rather than cmd.cmd.name.

Don't export an object, use individual named exports instead:
export const name = testFunc";
export const desc = "Test";
export function execute(name, args) {
console.log("Test ()");
}
Alternatively, change your import statement to use destructuring:
import(`./commands/${file}`).then(({cmd}) => {
console.log(cmd.name);
})

Related

How can we use a mobx store in utility function?

How can we use a mobx store in utility function?
I have a mobx store and a utility function to make a axio call, I want to use stote value in the utility, how can I do this?
// Store example
export default class SampleStore {
#observable title = "Coding is Love";
#observable user = {
userId: 1,
};
#action
setUser(user) {
this.user = user;
}
#action
updateUser(data) {
this.user = { ...this.user, ...data };
}
#action
clearUser() {
this.user = undefined;
}
#action
setTitle(title) {
this.title = title;
}
}
// Utility function in different file
export function makeApiCall () {
// Use SampleStore here
}
Depends on how you actually initialize your store, how your app is organized and many other factors.
Most simple way is to have singleton store and then you just import it and use directly:
// export an instance instead
export const sampleStore = new SampleStore()
// .. util fil
import { sampleStore } from './SampleStore.js'
export function makeApiCall () {
sampleStore.setUser()
}
Another way is just to pass store to the function, for example if you want to make this call inside useEffect or something:
// Make function accept store as an argument
export function makeApiCall (sampleStore) {
sampleStore.setUser()
}
// ... inside of some React component
// get store from the context (I guess you will have it at that point)
const { sampleStore } = useStores()
useEffect(() => {
// and just pass to the function
makeApiCall(sampleStore)
}, [])

rename named export without export default

I do have an issue when I want to decorate my export with a wrapper.
I have a wrapper/hof function that encapsulate the real function like this:
import { withSth } from './anotherFile'
import { someConst } from './someConst'
const myFunc = () => {}
export {
myFunc: withSth(someConst, myFunc)
}
Parsing error: ',' expected.
This does not work while this work:
import { withSth } from './anotherFile'
import { someConst } from './someConst'
const myFunc = () => {}
module.exports = {
myFunc: withSth(someConst, myFunc)
}
The only way i can do this is like this:
import { withSth } from './anotherFile'
import { someConst } from './someConst'
const myFuncX = () => {}
const myFunc = withSth(someConst, myFuncX)
// OR
// const myFync = withSth(someConst, () => {})
// but it lose readability
module.exports = {
myFunc
}
My point is how can I do the same thing with export and without using default export and renaming all my function
module.exports = {
methodA: withSth(param, methodA),
methodB: withSth(param, methodB),
methodC: withSth(param, methodC),
methodD: withSth(param, methodD),
}
Unlike Commonjs modules (with module.exports), ES6 modules do not export values but variable bindings. You must declare a variable1, you cannot export something unnamed. So your choices are only
export const myFunc = withSth(someConst, myFuncX);
const myFuncX = () => {};
export const myFync = withSth(someConst, () => {});
const myFuncX = () => {};
const myFyncY = withSth(someConst, () => {});
export { myFuncY as myFunc }
1: with the exception of export default …;, which implicitly declares a variable with an unforgeable name for you. But you want multiple named exports.

Assign object to a variable before exporting as module default warning

import axios from 'axios'
const baseUrl = 'http://localhost:3001/persons';
const getAll = () => {
return axios.get(baseUrl);
}
const create = (newObject) => {
return axios.post(baseUrl,newObject);
}
export default {
getAll:getAll,
create:create
}
Using axios to fetch data from server(in reactjs from json server), everything works fine but console shows this warning:
Line 13:1: Assign object to a variable before exporting as module default.
How to remove this warning??
You need to assign the object to a variable before exporting it as default.
const exportedObject = {
getAll,
create,
};
export default exportedObject;
You can also export the function individually to get rid of the warning:
import axios from 'axios';
const baseUrl = 'http://localhost:3001/persons';
export const getAll = () => { return axios.get(baseUrl); }
export const create = (newObject) => { return axios.post(baseUrl, newObject); }
You can remove this warning by just adding the comment "// eslint-disable-next-line" before export.
import axios from 'axios'
const baseUrl = 'http://localhost:3001/persons';
const getAll = () => {
return axios.get(baseUrl);
}
const create = (newObject) => {
return axios.post(baseUrl,newObject);
}
// eslint-disable-next-line
export default {
getAll:getAll,
create:create
}

How to convert class with static items to module file

I have a class like this:
export default class {
static myConnection = GHD.initConnection();
static getCards = () => this.myConnection.getCards();
}
And I call it as:
import connector from '../path.js';
connector.getCards();
I would like to convert this class with static items to module basically I don't want to use class.
Is this possible?
I tried something like:
module.exports {
myConnection: GHD.initConnection();
getCards: () => this.myConnection.getCards();
}
but this doesn't work.
Update with real code values requested in comments:
export default class {
static firebaseReference = RNFirebase.initializeApp();
static getDatabase = () => this.firebaseReference.database();
static getUser = () => this.firebaseReference.auth().currentUser;
}
You're probably looking for
export const myConnection = GHD.initConnection();
export const getCards = () => myConnection.getCards();
then
import * as connector from '../path.js';
connector.getCards();
or
import { getCards } from '../path.js';
getCards();
If you must keep compatibility with the default import syntax, you can use
export const myConnection = GHD.initConnection();
export const getCards = () => myConnection.getCards();
/** #deprecated */
export default { myConnection, getCards };

Most common pattern to implement a settable module scoped variable

I am writing a client to talk to a server API in JavaScript. I have an OOP background but am trying to embrace modern EcmaScript.
So I started with this:
customerApi.js:
const baseUrl = "http://myapi";
export const getCustomers = () => { /* get customer code */ }
export const addCustomer = cust => {}
export const deleteCustomer = id => {}
All the functions use baseUrl.
Now I want to refactor so that the code that uses customerApi.js sets/passes in the baseUrl, and the only ways I have come up with are -
make it a class:
export default class customerApi {
constructor(baseUrl) {
this._baseUrl baseUrl;
}
}
Pass it into every method:
export const getCustomers = (baseUrl) => { /* get customer code */ }
export const addCustomer = (baseUrl,cust) => {}
export const deleteCustomer = (baseUrl,id) => {}
Wrap in a function:
const moduleFn = baseUrl => (
return {
getCustomers: () => { /* get customer code */ }
addCustomer: (cust) => {}
deleteCustomer: (id) => {}
}
)
export default moduleFn;
These are just examples.
What is the most common pattern to implement a "settable" variable on a module?
I would go with the function approach
export default function(baseUrl){
return Object.freeze({
getCustomers: () => { /* get customer code */ }
addCustomer: (cust) => {}
deleteCustomer: (id) => {}
})
}
This is because all the functions have closure on the baseUrl and no extra work is required.
Client code can simply
import yourmodule from 'yourmodule';
var derp = yourmodule('www.derp.com')

Categories