How to export multiple functions ES6 - javascript

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.

you can use export
export function sendData() {...}
and you can import like this
import fetchData, { sendData } from '/src/utility/db_handler.js;'

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
by using import { function1, function2} from "./exportedFunctionFile" make sure you are using same function name as you exported!
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

export the functions in an object
export default {
sendData: sendData,
fetchData: fetchData
}
then to use
import * as DBHandler from '#/src/utility/db_handler'
...
DBHandler.sendData()

On the function files
func1(params) {
...
}
func2(params) {
...
}
export default default {
function1: function1,
function2: function2
}
On the other file
import * as _ from './module address'
then
_.default.func1.call(args)
_.default.func2.call(args)

Related

React does not recognize defined function

The problem occurs when I do try to fire onClick function linked with the ButtonWithDate component ( it is being inherited from the parent component ):
<Button
variant="extendedFab"
onClick={this.props.updateDateAndHour}
color="primary">
Display Date
</Button>
Once I use it, the following error occurs:
TypeError: _services_API__WEBPACK_IMPORTED_MODULE_7__.default.getResponse is not a function
Bind of updateDateAndHour func:
<ButtonWithDate updateDateAndHour={this.updateDateAndHour}></ButtonWithDate></center>
App.js
import React, { Component } from 'react';
import API from './services/api';
import ButtonWithDate from './components/ButtonWithDate';
class App extends Component {
constructor() {
super();
this.state= {
'day': '',
'month': '',
'year': ''
};
this.API = API;
}
updateDateAndHour = () => {
console.log(this);
var self = this;
API.getResponse().then((res) => {
var local_date = res.date.split('-');
self.setState({
day: local_date[0]
})
self.setState({
day: local_date[1]
})
self.setState({
day: local_date[2]
})
});
}
render() {
return (
<div>
<center>
<ButtonWithDate updateDateAndHour={this.updateDateAndHour}></ButtonWithDate></center>
</div>
);
}
}
export default App;
services/api.js
import axios from 'axios';
const URL = 'https://...';
export default class API{
getResponse() {
axios.get(URL)
.then(result => {
return result
})
.catch(error => {
return null;
});
}
};
components/ButtonWithDate.js
import React from 'react';
import PropTypes from 'prop-types';
import Button from '#material-ui/core/Button';
export default class ButtonWithDate extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="button-container">
<Button
variant="extendedFab"
onClick={this.props.updateDateAndHour}
color="primary">
Display Date
</Button>
</div>
)
}
}
ButtonWithDate.propTypes = {
onClickButton: PropTypes.func
}
When I do use a console.log along with the function name, I can easily access the content of it:
updateDateAndHour = () => {
console.log(getResponse);
getResponse()...
but once I invoke getResponse(), an exception takes a place.
Screenshot of the error:
first of all sounds like there is a problem with this binding;
class App extends Component {
constructor() {
...
this.updateDateAndHour = this.updateDateAndHour.bind(this);
}
updateDateAndHour(){
...
})
...
}
you can use babel proposal class properties to automatically to those bindings for you instead of manually doing every time
checkout this link for further reading;
However the main problem is in your ./api/ it's simpler to export getResponse() like below
services/api.js
import axios from 'axios';
const URL = 'https://...';
const getResponse = () => {
axios.get(URL)
.then(result => {
return result
})
.catch(error => {
return null;
});
}
export default getResponse;
EDIT:
for the sake the debugging cut getResponse() body in your /api/ and use it in updateDateAndHour(){ ... }) to see if it's working or not ( to see if the problem is in importing or the function itself )
Ok, the issue was connected with with usage of
.then((res) => {
var local_date = res.date.split('-');
self.setState({
day: local_date[0]
})
getResponse() function was not returning a new Promis object. That was the problem.
Quick-fix:
api.js
import axios from 'axios';
const DATE_JSON_URL = 'https://...';
function getResponse() {
return new Promise((resolve, reject) => {
axios.get(URL)
.then(result => {
resolve(result);
})
.catch(error => {
reject(error);
})
})
}
export default getResponse;

How to call an action (NuxtJs)

I'm trying to call an action in my vue from my store.
This is my file aliments.js in my store:
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex, axios);
export const state = () => ({
aliments: {},
})
export const mutations = () => ({
SET_ALIMENTS(state, aliments) {
state.aliments = aliments
}
})
export const actions = () => ({
async getListAliments(commit) {
await Vue.axios.get(`http://localhost:3080/aliments`).then((response) => {
console.log(response);
commit('SET_ALIMENTS', response);
}).catch(error => {
throw new Error(`${error}`);
})
// const data = await this.$axios.get(`http://localhost:3080/aliments`)
// commit('setUser', user)
// state.user = data;
// return state.user;
}
})
export const getters = () => ({
aliments (state) {
return state.aliments
}
})
I want to diplay a list of aliments in my vue with :
{{ this.$store.state.aliments }}
I call my action like this :
<script>
import { mapGetters, mapActions } from 'vuex'
export default {
computed: {
...mapGetters(['loggedInUser', 'aliments']),
...mapActions(['getListAliments']),
getListAliments() {
return this.$state.aliments
}
}
}
</script>
I don't understand where is my mistake :/
NB: I also tried with a onclick method on a button with a dispatch('aliments/getListAliments')... but doesn't work...
The problem is that you're mapping your actions in the "computed" section of the component, you should map it in the "methods" section !
Hi and Welcome to StackOverflow
to quickly answer to your question, you would call an action as:
this.$store.dispatch('<NAME_OF_ACTION>', payload)
or though a mapActions as
...mapActions(['getListAliments']), // and you call `this.getListAliments(payload)`
or yet
...mapActions({
the_name_you_prefer: 'getListAliments' // and you call `this.the_name_you_prefer(payload)`
}),
for getters, it's the same process, as you already have 2 definitions ['loggedInUser', 'aliments'] you simply call the getter like if it was a computed value <pre>{{ aliments }}</pre>
or when we need to do a bit more (like filtering)
getListAliments() {
return this.$store.getters['aliments']
}
But I can see your store is as we call, one-to-rule-them-all, and because you are using Nuxt, you can actually leverage the module store very easy
as your application grows, you will start store everything in just one store file (the ~/store/index.js file), but you can easily have different stores and instead of what you wrote in index.js it can be easier if you had a file called, taken your example
~/store/food.js with
import axios from 'axios'
export const state = () => ({
aliments: {},
})
export const getters = {
aliments (state) {
return state.aliments
}
}
export const mutations = {
SET_ALIMENTS(state, aliments) {
state.aliments = aliments
}
}
export const actions = {
async getListAliments(commit) {
await axios.get('http://localhost:3080/aliments')
.then((response) => {
console.log(response);
commit('SET_ALIMENTS', response.data);
}).catch(error => {
throw new Error(`${error}`);
})
}
}
BTW, remember that, if you're using Nuxt serverMiddleware, this line
axios.get('http://localhost:3080/aliments')...
would simply be
axios.get('/aliments')...
and to call this store, all you need is to prefix with the filename, like:
...mapActions(['food/getListAliments'])
// or
...mapActions({ getListAliments: 'food/getListAliments' })
// or
this.$store.commit('food/getListAliments', payload)
another naming that could help you along the way:
on your action getListAliments you're actually fetching data from the server, I would change the name to fetchAliments
on your getter aliments you're actually returning the list, I would name it getAllAliments
have fun, Nuxt is amazing and you have a great community on Discord as well for the small things :o)
EDIT
also remember that actions are set in methods
so you can do:
...
export default {
methods: {
...mapActions(['getListAliments]),
},
created() {
this.getListAliments()
}
}
and in your Store action, please make sure you write
async getListAliments({ commit }) { ... }
with curly braces as that's a deconstruction of the property passed
async getListAliments(context) {
...
context.commit(...)
}

React Redux not dispatching API Call to delete player

I am trying to migrate my previously working local state to redux. Now loading available Players works just fine, but deleting will somehow stop in the playerActions.js file, where I dispatch and then return an API Call. So to further give details here are my code parts in relevance:
PlayerPage.js (Component):
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { loadPlayers, deletePlayer } from '../../redux/actions/playerActions';
import PlayerForm from './playerform';
import PlayCard from './playercard';
import PropTypes from 'prop-types';
import { toast } from 'react-toastify';
class PlayerPage extends Component {
constructor(props) {
super(props);
this.handleDeletePlayer = this.handleDeletePlayer.bind(this);
state = {};
componentDidMount() {
const players = this.props;
players.loadPlayers().catch(err => {
alert('Loading players failed. ' + err);
});
}
handleDeletePlayer = player => {
toast.success('Player deleted');
try {
deletePlayer(player);
} catch (err) {
toast.error('Delete failed. ' + err.message, { autoClose: false });
}
};
render() {
const styles = {
margin: '20px'
};
return (
<div className="container-fluid">
<div>
<h2 style={styles}>Add Player</h2>
<div className="container-fluid">
<PlayerForm handleAddNewPlayer={this.handleAddPlayer} />
</div>
</div>
<hr></hr>
<div>
<h2 style={styles}>Available Player</h2>
<div className="container-fluid">
{this.props.players.map(player => (
<PlayCard
player={player}
key={player.id}
imageSource={`${process.env.API_URL}/${player.profileImg}`}
onDeletePlayer={this.handleDeletePlayer}
/>
))}
</div>
</div>
</div>
);
}
}
PlayerPage.propTypes = {
players: PropTypes.array.isRequired
};
function mapStateToProps(state) {
return {
players: state.players
};
}
const mapDispatchToProps = {
loadPlayers,
deletePlayer
};
export default connect(mapStateToProps, mapDispatchToProps)(PlayerPage);
And the Action being called is in here:
playerActions.js:
import * as types from './actionTypes';
import * as playerApi from '../../api/playerApi';
export function loadPlayersSuccess(players) {
return { type: types.LOAD_PLAYERS_SUCCESS, players };
}
export function deletePlayerOptimistic(player) {
return { type: types.DELETE_PLAYER_OPTIMISTIC, player };
}
export function loadPlayers() {
return function(dispatch) {
return playerApi
.getAllPlayers()
.then(players => {
dispatch(loadPlayersSuccess(players));
})
.catch(err => {
throw err;
});
};
}
export function deletePlayer(player) {
console.log('Hitting deletePlayer function in playerActions');
return function(dispatch) {
dispatch(deletePlayerOptimistic(player));
return playerApi.deletePlayer(player);
};
}
The console.log is the last thing the app is hitting. But the API Call is never made though.
API Call would be:
playerApi.js:
import { handleResponse, handleError } from './apiUtils';
const axios = require('axios');
export function getAllPlayers() {
return (
axios
.get(`${process.env.API_URL}/player`)
.then(handleResponse)
.catch(handleError)
);
}
export function deletePlayer(id) {
return (
axios
.delete(`${process.env.API_URL}/player/${id}`)
.then(handleResponse)
.catch(handleError)
);
}
I was like spraying out console.log in different places and files and the last one I am hitting is the one in playerActions.js. But after hitting it the part with return function(dispatch) {} will not be executed.
So if someone could point me in a general direction I'd be more than grateful.
It looks like you are calling your action creator deletePlayer but you aren't dispatching it correctly. This is why the console.log is being called but not the method that does the request.
I'd recommend taking a look at the documentation for mapDispatchToProps to fully understand how this works. In your example, you should just need to change the call to deletePlayer in your PlayerPage component to this.props.deletePlayer() to use the action creator after it's been bound to dispatch properly.
this how the mapDispatchToProps should be:
const mapDispatchToProps = dispatch => {
return {
load: () => dispatch(loadPlayers()),
delete: () => dispatch(deletePlayer()),
}
}
then call load players with this.props.load() and delete player with this.props.delete()

In the nuxt project, other files are introduced separately into the store

sorry about my english, How can i in other js files use vuex.store in nuxt project
in store
export const state = () => ({
token: 'test',
name: '',
avatar: ''
}),
export const mutations = {
SET_TOKEN: (state, token) => {
state.token = token
}
},
export const getters = {
token: state => {
return state.token
}
}
in test.js
export function() => {
//how can i updata vuex token?
}
export function() => {
//how can i getter vuex token?
}
export default ({ app, store, route, redirect }) => {
some code
}
it can't work
Wanted to know if it's good practice to do that and what would be the best way to do that?
A basic implementation would look like this
import { mapState, mapGetters, mapActions } from 'vuex'
export default {
computed: {
// you only need State OR Getter here not both!!! You don't need a
// getter for just returning a simple state
...mapState('yourStoreName', ['token'])
...mapGetters('yourStoreName', ['token']),
},
methods: {
methodThatNeedsToChangeState (){
this.setToken('newToken')
},
...mapActions('yourStoreName', ['setToken']),
}
}
In your store you need actions though, you don't call mutations directly! Because Mutations can't be asynchronous.
export const actions = {
setToken: (context, token) => {
context.commit(SET_TOKEN, token)
}
},
I would highly recommend you to study the Vuex documentation in more detail.
https://vuex.vuejs.org/guide/

Error: [vuex] expects string as the type, but found undefined

Studying Vuex. I wrote a simple login page against the example project and the document, but when I tried to use a action function, the developer tool just warned me
Here is my code:
src/views/Login.vue
handleLogin (formName) {
this.$refs[formName].validate(valid => {
if (valid) {
// to do
this.$store.dispatch('user/login', this.loginUser)
} else {
......
})
}
})
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/User/user'
// import info from './modules/info'
Vue.use(Vuex)
export default new Vuex.Store({
strict: false,
modules: {
user,
// info
}
})
/src/store/modules/User/actions.js
export const userActions = {
login({commit}, loginUser) {
commit(LOGIN)
axios.post(`${ API_BASE_USER }/login`, loginUser)
.then(res => {
console.log(res)
if (res.status == 200) { commit(LOGIN_SUCCESS, res.data) }
else { commit(LOGIN_FAILURE, res.data) }
})
}
}
/src/store/modules/User/user.js
import { userActions } from './actions'
import { userMutations } from './mutations'
export default {
namespaced: true,
state: {
token: ''
},
actions: Object.assign({}, userActions),
mutations: Object.assign({}, userMutations)
}
I got it.
The origin mutations-type.js export const LOGIN = LOGIN
But the correct mutation-type.js should be export const LOGIN = 'LOGIN'
This can also happen when you call $store.commit() without providing it an argument
Had a similar situation, where the Mutation name started with a CAP (), but the actual mutation started with a non cap():
RetrieveContractorSuccess: 'retrieveContractorSuccess'
(before was RetrieveContractorSuccess: 'RetrieveContractorSuccess')

Categories