简体   繁体   中英

concatenation of the variable in the middle of the imported string in javascript

I create a special js file in which I will map all my api endpoints that I will import into my redux-saga:

export const API_BASE_URL = 'https://localhost:3000/api';
export const USERS = '/Users';

export default {
  users: {
    example: `${API_BASE_URL}${USERS}/example`,
    checkEmail: `${API_BASE_URL}${USERS}${HERE_I_NEED_MY_VARIABLE}/checkEmail`,
  },
};

but my endpoint looks like this:

import { api } from 'utils';

export function* checkEmail({ value }) {
  const requestURL = `https://localhost:3000/api/Users/${value}/checkEmail`;
  // I would like to do this: (pseudocode) const requestURL = `${api.users.checkEmail} + ${value}`
  ...
};

How can I do it to make it look nice and professional? Does the latest js allow you to do something like this?

You could store your urls into functions, this way you could pass some parameters to fill the gaps.

export const API_BASE_URL = 'https://localhost:3000/api';
export const USERS = '/Users';

export default {
  users: {
    example: () => `${API_BASE_URL}${USERS}/example`,
    checkEmail: (variable) => `${API_BASE_URL}${USERS}/${variable}/checkEmail`,
  },
};

then you call it like any other functions.

import { api } from 'utils';

export function* checkEmail({ value }) {
  const requestURL = `${api.users.checkEmail(value)}`
  ...
};

I've also replace your string concatenation in your string template because i'm not sure that's what you wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM