Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export multiple functions ES6

I'm working in a vue project, I'm very new to vue.

We have a db_handler.js in out /src/utility folder. It looks like this:

import fakeApiCall from "./mock";
import axios from "axios";
import { DEBUG_MODE, API_ENDPOINT } from "./namespaces";

function fetchData(method, slug, payload) {
  //axios.defaults.headers.withCredentials = true;
  //return (!DEBUG_MODE) ? axios[method](`${API_ENDPOINT}${slug}`, payload) : fakeApiCall(slug);
  return axios[method](`${API_ENDPOINT}${slug}`, payload);

  /*var url = "http://localhost:8080" + slug

  return axios({
    method: method,
    url: url,
    headers: {
        'Authorization': payload
    }
  });*/
}

function sendData(method, slug, payload) {
  axios[method](`${API_ENDPOINT}${slug}`, payload);
}

export default fetchData

What I need to know: How can I export my sendData()? They used a short syntax so far because they only exported one function. How can I export multiple functions? I also want the names to remain "fetchData" and "sendData"

EDIT: I tried to apply the approaches of Iamhuynq and Bergi, but now something goes south. I am importing the functions first and foremost in moduleUser.js and authUser.js which reside in /src/store/modules. The authUser.js is used for the identification of the user, so of course it is used in the login screen. When I now try to login, I get "Type Error: Object undefined". I guess this is because the functions returning the server response are somehow failing or not found.

The codebase connected to this behavior is the Login screen, the db_handler which Ive already shown you and a module called "moduleAuth.js".

First, the login screen looks like this:

<template>
  <div>
    <h1>Login</h1>
    <p>Name:</p>
    <div class="inputbox">
      <input ref="username" type='text' v-on:keydown.enter="userLogin">
    </div>
    <p>Password:</p>
    <div class="inputbox">
      <input class="inputbox" ref="password" type='password' v-on:keydown.enter="userLogin">
    </div>
    <p>{{error}}</p>
    <button v-on:click='userLogin'>Login</button>
  </div>
</template>

<script>
import store from "../store/store";

import { AUTH_REQUEST } from "../store/actions/auth";

export default {
  data () {
    return {
      error: ""
    }
  },
  methods: {
    userLogin: function(){
      this.error = '';
      store.dispatch(AUTH_REQUEST,{username: this.$refs.username.value, password: this.$refs.password.value})
      .then((res) => {
        this.$router.push({path: '/profile'});
      })
      .catch((err) => {
        this.error = err;
      });
      this.$refs.password.value = '';
    }
  }
}
</script>

<style>
.inputbox{
  width: 25%;
}
</style>

moduleAuth.js, from which the AUTH_REQUEST vue-action is coming, looks like this:

import axios from "axios";
import Vue from 'vue';
import Vuex from 'vuex';
import {fetchData, sendData} from "../../utility/db_handler";

import { USER_REQUEST } from "../actions/user";
import { AUTH_REQUEST, AUTH_LOGOUT, AUTH_FAIL, AUTH_SUCCESS } from "../actions/auth";
import { METHOD_POST, JWT } from "../../utility/namespaces";

Vue.use(Vuex);

const storeAuth = {
  state: {
    token: localStorage.getItem(JWT) || '',
    loginState: ''
  },
  getters: {
    isAuthenticated: state => !!state.token,
    getLoginState: state => state.loginState
  },
  mutations: {
    [AUTH_REQUEST]: (state) => {
      state.loginState = 'pending';
    },
    [AUTH_FAIL]: (state) => {
      state.loginState = 'error';
    },
    [AUTH_SUCCESS]: (state, mToken) => {
      state.loginState = '';
      state.token = mToken;
    },
    [AUTH_LOGOUT]: (state) => {
      return new Promise ((resolve, reject) =>{
        state.loginState = '';
        state.token = '';
        localStorage.removeItem(JWT);
        resolve();
        //Catch?
      })
    }
  },
  actions: {
    [AUTH_REQUEST]: ({ commit, dispatch }, uObj) => {
      return new Promise((resolve, reject) => {
        commit(AUTH_REQUEST);
        fetchData(METHOD_POST, '/login',{
            username: uObj.username,
            password: uObj.password
          }).then(function (res) {
          commit(AUTH_SUCCESS,res.headers.authorization);
          localStorage.setItem(JWT,res.headers.authorization);
          axios.defaults.headers.common['Authorization'] = res.headers.authorization;
          dispatch(USER_REQUEST);
          resolve(res.data);
        }).catch(function(err) {
          commit(AUTH_FAIL);
          reject(err);
        })
      })
    },
    [AUTH_LOGOUT]: ({ commit}) => {
      commit(AUTH_LOGOUT);
    }
  }
}

export default storeAuth

Now, if just roll back the changes to the export/import sections, everything works. So the problem should definitely be connected to this.

like image 991
Narktor Avatar asked Aug 09 '26 09:08

Narktor


2 Answers

you can use export

export function sendData() {...}

and you can import like this

import fetchData, { sendData } from '/src/utility/db_handler.js;'
like image 96
iamhuynq Avatar answered Aug 10 '26 22:08

iamhuynq


Here my suggestion is, if you are exporting more then one function, you should use export method instead of export default. It will make your code more readable and ll use for future debugging.

export function function1(params) {
 .......
}

export function function2() {
 ......
}

Here there is a two way to import functions

  1. by using import { function1, function2} from "./exportedFunctionFile" make sure you are using same function name as you exported!
  2. other method is use * as yourVariableName example import * as myFunctions from "./exportedFunctionFile" this would use when you are exporting too many functions now you can use your imported functions as myfunctions.function1()

if you want to export using default key word, export functions as object example export default {function1,function2} and you could use it like import * as myFunctions from "./exportedFunctionFile" which is similar as a second way of importion.

Hope it will Help you

like image 29
manan5439 Avatar answered Aug 10 '26 23:08

manan5439



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!