Get function inside default export function - javascript

I have function inside user.js with default export like this
export default {
var getListFriends = async (accessToken) =>{
}
....other function
return {
getListFriends,
...other function...
}
}
then I import it to index.js
import userService from './user';
Then I will add only index.js to plugin.
I can call this.$userService (it shows as anonymous function) but this.$userService.getListFriends return undefined.
How can I call function getListFriends from import.
Thank you very much.

where is user.js?
if its inside plugins directory, you have to use inject to add it to your nuxt.
then you can access it via nuxt object inside your code.
see this example from nuxt docs:
export default ({ app }, inject) => {
// Inject $hello(msg) in Vue, context and store.
inject('hello', msg => console.log(`Hello ${msg}!`))
}
you can see the full document here

ok now for this to work the way you want you need to change your user.js file,
export default {
friends: () => {
console.log('hi bro');
},
notFriends: () => {
console.log('go away man im not your bro');
}
};
something like this.
you dont need inject or app in your user.js.
and your code problem is that you are defining a function and trying to access it's inner values from the outside like:
function boo() {
var b = 0;
}
you can not access the value of b with boo.b. its a local variable to the boo function
instead create a object and have multiple functions inside your object

Related

How to access nuxt `$config` in Vuex state? Only access method is through store actions methods?

I have used to dotenv library to use .env file, but I have to change runtimeConfig because I realized it was easy to expose my project secret key.
In my latest project, I have used nuxt "^2.14" and mode is SPA.
So I only use "publicRuntimeConfig" in nuxt.config.ts like that.
.env
Test_BASE_URL:'https://test.org'
nuxt.config.ts
export default {
publicRuntimeConfig:{baseURL: proccess.env.Test_BASE_URL||''}
}
I can use env like that in vue file.
sample.vue
<script>
export default {
mounted(){
console.log(this.$config.baseURL)
}
}
</script>
But I couldn't use "$config" in store's state.
I tried to write that but it always return "undefied"
index.ts
export const state = (context) => ({
url:context.$config
})
I have referred the this guys solutions
and changed state's value through the actions method.
I have used SPA, so I made method like 'nuxtServerInit'as plugins.
plugins/clientInit.ts
import {Context} from "#nuxt/types";
export default function (context:Context) {
context.store.dispatch('initEnvURL',context.$config)
}
index.ts
interface State {
testURL: string
}
const state = () => ({
testURL:''
})
const mutations = {
setTestURl(state:State,config:any) {
state.testURL = config.baseURL
}
const actions = {
initEnvURL({commit},$config) {
commit('setTestURl',$config)
}
}
export default {state,mutations,actions}
I success to change state value through actions methods above,
but I don't know why "context" can't use store/state objects directly.
Does anyone know how to use $config in store/state?
or is it impossible only way to use $config through actions method like above?
That's because in Vuex, only actions actually receive the app context.
State, Mutations and Getters can't access it by design.
Your initial state should be contextless, i.e. with values that doesn't depend on the runtime execution.
Mutations are stateless, they just take a parameter and update the state. That's all. Contextful parameters should be coming from the caller.
Getters are just reactive state transformations, and should not rely on context properties, that would be messing with the Vuex module state.
So yes, what you have to do it initialise your store within the nuxtServerInit actions (or from a plugin for SPA apps):
nuxtServerInit({ store, config } ) {
store.commit('UPDATE_BASE_URL', config.baseUrl)
}
It does NOT show up through the type system even when using #nuxt/types.
Access it like this in store/index.ts or store/module.ts:
import { ActionTree, MutationTree } from 'vuex'
const actions: ActionTree<ModuleState, RootState> = {
async yourActionName({ commit }, payload): Promise<void> {
try {
let url = this.app.$config.baseURL + "/path"; // <- config is accessed here.
const res = await this.$axios.get<number>(url);
commit("mutateState", res.data);
return;
} catch (error) {
// Error handling
}
},
};
My nuxt.config.js looks like:
export default {
...
publicRuntimeConfig: {
baseURL: process.env.BASE_URL || 'http://localhost:5000/api',
}
...
};

What is the difference between React Store to global objects?

We can use something like this:
// GlobalStore.js
import { store } from 'react-easy-store'
const _store = store({a: 1})
export default _store
And use it like this:
// any file.js
import GlobalStore from 'path/to/global-store'
import { view } from 'react-easy-state'
export default view(() => {
console.log(GlobalStore.a) // 1
})
We could also create a file like this:
// GlobalStore.js
export default {
a: 1
}
and import it like this:
// any file.js
import GlobalStore from 'path/to/global-store'
export default () => {
console.log(GlobalStore.a) // 1
}
We also can add "inner methods" either in React store and either in any JS object like this:
{
...
someMethod() { // do something with the object }
}
Also, when using "regular" js object and import it from elsewhere in the app, it always be "ready" and up to date with the new defined info's, for example: if file A updates the GlobalScope, when we navigate or import file B that also imports file A, it will be up to date with the new data that file A leaved.
In addition we have Redux which is much complex than the 'react-easy-store' that I mentioned above.
So what are the differences / benefits?
Why installing a third party dependency if we can actually achieve the same thing with basic JS?

Chain js function and then method in vue.js

Within a Vue component, I am calling a function from a separate JS file. I then need to call a method in my component just after this first function is completed:
My .vue component:
import myFunction from '#/components/functions';
export default {
name: 'test',
components: {
myFunction,
},
created(){
if (....) {
myFunction.function1(myParam)
.then((response) => {
this.method2();
});
},
methods:{
method2(){
something;
},
}
};
My separate functions.js file:
export default {
function1(myParam) {
...
return true;
},
};
I tried several things such as the last one shown in my code which gives me a
.function1(...).then is not a function
I am sure it is not that complicated but can not find the correct syntax.
The function in your other file could return a Promise or it can except a callback from your view component. Also, if you set this equal to self/vm and then use vm.method2(), this is because in the then callback this is defined in scope of that function not the Vue component.

Correct way to export object in es6 module

I'm trying to export an my module as an object but exporting it seems an 'anti pattern' (https://medium.com/#rauschma/note-that-default-exporting-objects-is-usually-an-anti-pattern-if-you-want-to-export-the-cf674423ac38)
So I was wondering what's the correct way to export an object and then use it as
import utils from "./utils"
`
utils.foo()
Currently I'm doing like so
/** a.js **/
function foo(){
//...
}
export {
foo
}
/** b.js **/
import * as utils from "a";
utils.foo()
is it correct like so? Do I maintain the tree-shaking feature?
thanks
If the object you want to import/export only contains some functions (as I assume due to the Utils name), you can export the functions separately as follows:
export function doStuff1() {}
export function doStuff2() {}
And import like this:
import {doStuff1, doStuff2} from "./myModule";
However, if the object you want to export holds state in addition to methods, you should stick to a simple export default myObject. Otherwise, calling the imported methods won't work as intended, since the context of the object is lost.
As an example, the following object should be exported as a whole, since the properties of the object should stay encapsulated. Only importing and calling the increment function would not mutate myObject since the context of the object cannot be provided (since it's not imported as a whole).
const myObject = {
counter: 0,
increment: function() {
this.counter++;
}
}
export default myObject;
es6 native way to do this:
// file1.es6
export const myFunc = (param) => {
doStuff(param)
}
export const otherFunc = ({ param = {} }) => {
doSomething({ ...param })
}
// file2.es6
import { otherFunc } from './file1.es6'
import * as MyLib from './file1.es6'
MyLib.myfunc(0)
MyLib.otherFunc({ who: 'Repley' })
otherFunc({ var1: { a1: 1 } })
And so on.

How to access props in other functions of imported modules

Let say i created a basic modules with simple functions like helper.js
export function HelloChandu() {
//How to access navigator props from here.
}
export function HelloTester() {
HelloChandu();
}
Then I imported this module in my component as import * as Helper from './helper';
In some element I then called onpress={Helper.HelloTester.bind(this)} So by this now I can access this.props in HelloTester function but I can not access this.props in HelloChandu function.
Question : How can I access this.props from any function in my helper.js module ? Like if there are 10-20 functions , and i don't have to pass as parameters around.
Thank You
I am afraid that if you want to access this.props in one of your functions you will need to pass this explicitily or to bind all the functions to the current this before using them.
There are several ways to do so.
function HelloChandu() {
alert(this.props);
}
function HelloTester() {
HelloChandu.apply(this);
// HelloChandu.call(this);
// HelloChandu.bind(this)();
// this::HelloChandu(); // Experimental!
}
const obj = {
props: 'my props'
}
HelloTester.bind(obj)()
An alternative way would be to wrap all the functions in another function.
function helpers() {
const functions = {
HelloChandu: () => {
alert(this.props);
},
HelloTester: () => {
functions.HelloChandu();
}
};
return functions;
}
const obj = {
props: 'my props'
}
helpers.call(obj).HelloTester();
1.You can persist props to AsyncStorage, whenever you need, you can access this props.
2.Or if you are familiar with closure, you can do like this :
function Helper(ps) {
function test() {
console.log(ps.sex);
}
function test2() {
console.log(ps.name);
}
return {
test: test,
test2: test2,
}
}
var obj = Helper({name: 'abc', sex: 'male'});
obj.test();
obj.test2();
then you should export Helper, and import Helper from 'Helper.js'
export function HelloChandu(_this) {
//How to access navigator props from here.
}
export function HelloTester(_this) {
HelloChandu(_this);
}

Categories

Resources