Search code examples
javascriptvue.jsecmascript-6vuex

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.


Solution

  • you can use export

    export function sendData() {...}
    

    and you can import like this

    import fetchData, { sendData } from '/src/utility/db_handler.js;'