Can not import functions corretly in reactJS App? - javascript

I am having problem with import, I have a file like this :
import { TYPE_CONTRAT_UPDATE, CONFORMITE_UPDATE } from "./actionsTypes";
import { createAction } from "../../../../../../redux/Utilities";
const updateTypeContrat = (idContrat, data, success, error) =>
createAction(TYPE_CONTRAT_UPDATE.PUT_CALL, { idContrat, data, success,
error });
const updateConformiteContrat = (idContrat, data, success, error) =>
createAction(CONFORMITE_UPDATE.PUT_CALL, { idContrat, data, success,
error });
export default { updateTypeContrat, updateConformiteContrat};
I am trying to import as you can see variables in capital from my file actionsTypes, here is the file :
import { createPutTypes } from "../../../../../../redux/Utilities";
const TYPE_CONTRAT_UPDATE = createPutTypes("TYPE_CONTRAT_UPDATE");
const CONFORMITE_UPDATE = createPutTypes("CONFORMITE_UPDATE");
export default { CONFORMITE_UPDATE, TYPE_CONTRAT_UPDATE }
But I get an error :
Line 1: TYPE_CONTRAT_UPDATE not found in './actionsTypes' import/named
Line 1: CONFORMITE_UPDATE not found in './actionsTypes' import/named
Any help would be much appreciated.

You need to use named export instead of the default.
import { createPutTypes } from "../../../../../../redux/Utilities";
export const TYPE_CONTRAT_UPDATE = createPutTypes("TYPE_CONTRAT_UPDATE");
export const CONFORMITE_UPDATE = createPutTypes("CONFORMITE_UPDATE");

Those imports, as said from the error, should be named exports.
DEFAULT export
A default export (export default [...] is what will be imported when using import X from 'fileX'. There can be only one. No matter what you assign the import to in this case (here, you assign it to X), it will work
// fileX.js
export default Example;
You can do either
import X from 'fileX'; // works, X contains Example
import Example from 'fileX'; // same
...
NAMED exports
A named export (export const TYPE_CONTRACT = [...]) can be used as much as you want, however, the name of the import matters:
// fileX.js
export const Example = [...]
means that the import should be :
import { Example } from 'fileX'; // works properly, Example contains the export of fileX
import { X } from 'fileX'; // won't work, no way to know which export you're referring to
import Example from 'fileX'; // won't work either, this is not a default export.

Related

How to deconstruct properites on import based on theme?

I have a colors.ts file:
export const black = '#0C0C0C';
export const blue = '#22618E';
and when ever I want to import a specific color I import it like:
import {black} from 'Shared';
In my Shared folder I have an index.ts that exports the colors:
export * from './colors';
Now I want to be able to export and Import the same way when using a theme.
Example
colors.ts:
const DefaultTheme = {
black: '#0C0C0C',
blue: '#22618E',
}
const SpecialTheme= {
black: 'red',
blue: 'yellow',
}
export const ColorsBytheme = () => {
const context = myContext();
return context.Default? DefaultTheme :SpecialTheme;
}
Problem:
I can not deconstruct/import the properties directly, this gives me undefined:
import {black} from 'Shared';
How can I accomplish this?
EDIT:
I have also tried by using a self invoking function when exporting:
const ColorsBytheme = () => {
return DefaultTheme;
};
export default ColorsBytheme();
When I import
import { black } from 'Shared';
It is still undefined
Based on your code example, you are currently exporting ColorsBytheme as a function that generates/returns the theme object...therefore, your import/deconstruction would need to look something along the lines of:
import { ColorsBytheme } from "Shared"
const { black } = ColorsBytheme();
Another option if you wish to have a single line would be to use require instead of import:
const { black } = require("Shared").ColorsBytheme()
Variables that are imported are just that, static variables. Functions are not evaluated when they are imported, therefore, in order for the values to be dynamic, the function needs to be executed.

Export without destructuring

import { utils } from 'shared'
const {
pick,
get,
isEmpty,
sortBy,
orderObjectsArray,
isString
} = utils.lodashAlternative
export { pick, get, isEmpty, sortBy, orderObjectsArray, isString }
Above you can see exports , imagine I don't want to desctructure all of those functions , how can I do it ? I've tried to make export utils.lodashAlternative , but it will not work , also :
const {...data} = utils.lodashAlternative
export {...data}
Also will not work, it there any way to export it without discructuring ?
A simple way to export everything under utils.lodashAlternative is creating an alias and exporting that one instead.
There's no need to create an object and spread lodashAlternative inside.
You can't declare and export afterwards (unless you use as)!
Way 1: using default
import { utils } from 'shared'
const lodashAlternative = utils.lodashAlternative;
export default lodashAlternative;
Way 2: exporting directly
import { utils } from 'shared'
export const lodashAlternative = utils.lodashAlternative;
Way 3: export each one separately, to be able to import them separately
import {utils} from "shared";
const { foo, bar } = utils.lodashAlternative;
export { foo, bar };
import then:
// WITH WAY 1
import lodashAlternative from "lodash-alternative";
// WITH WAY 2
import {lodashAlternative} from "lodash-alternative";
// WITH WAY 3
import {foo, bar} from "lodash-alternative";
Blitz here

Jest Mocked Function not calling mocked axios instance function (returns undefined)

I started by following the answer in this StackOverflow Question
But I added a helper function I use which creates a new Axios instance with the auth token associated with the user.
Which looks a little like this:
import axios from "axios";
const mockAxios: jest.Mocked<typeof axios> = jest.createMockFromModule("axios");
// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => {
return mockAxios;
});
export const createAuthenticatedInstance = () => {
return mockAxios.create();
};
export default mockAxios;
Why does mockAxios.create() return undefined?
While the object 'mockAxios' (and the create function) is defined. When I actually call create it returns undefined despite the function being declared.
I know that I can side-step the issue by just returning mockAxios against but I'd like to understand why it doesn't work in the first place. What I'd expect is to return a new instance, which would be identical to mockAxios but it just returns undefined.
If you're creating an auto-mock (within __mocks__) it's meant to be a mock of the module and any helper functions are not expected to be within the module, but probably somewhere else with your code
Exmaple:
src/axios.utils.ts (utility module which exports axios and the function)
import axios from "axios";
export const createAuthenticatedInstance = (
...args: Parameters<typeof axios.create>
) => {
return axios.create(...args);
};
export default axios;
src/__mocks__/axios.ts (the axios mock)
const axios: jest.Mocked<typeof import("axios").default> = jest.createMockFromModule(
"axios"
);
axios.create.mockReturnThis();
export default axios;
src/api.ts (api implementation that uses the axios.util)
import axios from "axios";
import { createAuthenticatedInstance } from "./axios.utils";
const client = createAuthenticatedInstance({
baseURL: "http://example.com:80/main",
});
export default {
makeSomeReq: () => client.get<string>("/path"),
};
src/api.spec.ts (the test)
import api from "./api";
import axios, { AxiosResponse } from "axios";
jest.mock("axios");
const { get } = axios as jest.Mocked<typeof import("axios").default>;
describe("api", () => {
it("should have created an axios instance", () => {
expect(axios.create).toHaveBeenCalledWith({
baseURL: "http://example.com:80/main",
});
});
})
working example

Export component with and without hoc in one export

Is there any way to export component(s) with or without hoc in one export? I know I can do it like this:
export const TranslatedList = translate('components')(List);
export const PureList = List;
but is there any other way to do something like below:
export {
TranslatedList: translate('components')(List),
PureList: List,
};
and in index.js something like:
import { TranslatedList } from './List';
export default TranslatedList;
maybe stupid question but this will be really helpful to me
Maybe use node.js native exports like this:
module.exports = {
TranslatedList: translate('components')(List),
PureList: List,
};
And require it
const {TranslatedList, PureList} = require('list.js');
A little late to the party. I did not find a "great" solution to this issue, but this is an "ok" one, in my opinion.
const TranslatedDropzone = translate()(Dropzone)
const TranslatedDropzoneControls = translate()(DropzoneControls)
const TranslatedDropzonePreview = translate()(DropzonePreview)
const TranslatedFilePreview = translate()(FilePreview)
export {
TranslatedDropzone as Dropzone,
TranslatedDropzoneControls as DropzoneControls,
TranslatedDropzonePreview as DropzonePreview,
TranslatedFilePreview as FilePreview
}
export default TranslatedDropzone
In ES6 you simply cannot do this:
export {
TranslatedList: translate('components')(List),
PureList: List,
};
Instead you can try doing this:
const toExport = {
TranslatedList: translate('components')(List),
PureList: List,
};
export toExport;
To import, simply do this:
import { TranslatedList, PureList } from './list.js';

es6-module default export importing as undefined

I'm not sure what I'm missing here. I'm working on a project using jspm and es6-module-loader. I've got an module defined as follows:
import hooks from './hooks';
import api from './api';
import tools from './tools';
const StencilUtils = {
hooks: hooks,
api: api,
tools: tools,
};
export {hooks, api, tools};
export default StencilUtils;
/* global define */
(function(root) {
if (typeof define === 'function' && define.amd) {
define(function() {
return (root.stencilUtils = StencilUtils);
});
} else if (typeof module === 'object' && module.exports) {
module.exports = StencilUtils;
} else {
window.stencilUtils = StencilUtils;
}
}(this));
I'm importing this module in another file, and using it like so:
import utils from 'bigcommerce/stencil-utils';
utils.hooks.on('cart-item-add', (event, form) => {
// do stuff
});
When the files load, I get an error that utils is undefined. If I change the file to this:
import {hooks} from 'bigcommerce/stencil-utils';
hooks.on('cart-item-add', (event, form) => {
// do stuff
});
It works correctly. So, it appears something is not working correctly with the default export statement. Is there something obviously wrong here with the import or export statements that would cause this issue?
I think there are two things around this issue:
When you have named exports your access them through either importing as library or with object destruction.
Method 1
xyz.js
export const a = 1;
abc.js
import {a} from "xyz";
Method 2
xyz.js
export const a = 1;
abc.js
import {* as myModule} from "xyz";
console.log(myModule.a);
So in your case
export {hooks, api, tools};
it can be either
import * as utils from 'bigcommerce/stencil-utils';
or
import {hooks} from 'bigcommerce/stencil-utils';
Default export statement is not proper
It can either be
export default {
hooks: hooks,
api: api,
tools: tools,
};
Or
const StencilUtils = {
hooks: hooks,
api: api,
tools: tools,
};
export { StencilUtils as default };
Hope this will help you. For more details see this

Categories