React Constants inside a Function - javascript

I need help to export the constants. I am getting different errors when i try to search for this on google or other related topics at stackoverflow.
This is my Printer.jsx
import React, { useRef, useState } from "react";
// export individual features (can export var, let,
// const, function, class)
export let ePosDev = new window.epson.ePOSDevice();
export const ePosDevice = useRef();
export const printer = useRef();
export function connectFunction() {
ePosDevice.current = ePosDev;
ePosDev.connect("192.168.1.254", 8080, (data) => {
if (data === "OK") {
ePosDev.createDevice(
"local_printer",
ePosDev.DEVICE_TYPE_PRINTER,
{ crypto: true, buffer: false },
(devobj, retcode) => {
if (retcode === "OK") {
printer.current = devobj;
} else {
throw retcode;
}
}
);
} else {
throw data;
}
}); };
I need to add the const connect to the App.js so that if the App is starting the connection is also starting. The second is that i need to add the const print to ReactB.js-file so if content of ReactB.js-page is loading the print-request should be send.
Thanks for your help! Stuck at this since 5 hours and dont know how to deal with this problems.

It seems your main issue stems around how to export constants. I recommend checking out MDN for more info: https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export
Below is an excerpt on named exports that is relevant to your scenario.
// export features declared earlier
export { myFunction, myVariable };
// export individual features (can export var, let,
// const, function, class)
export let myVariable = Math.sqrt(2);
export function myFunction() { ... };
So for your example, it would just be a matter of adding declaring the const with export const connect = value; or adding export { connect }; after it is declared.

Related

React: Parsing error: Identifier 'publicKey' has already been declared

I'm new to React so please bear with my naming conventions:
How can I use the same name of 2 props from two different 3rd party components?
import { useWallet} from "#solana/wallet-adapter-react";
import { useMoralis } from "react-moralis";
export const SendOneLamportToRandomAddress = () => {
const { publicKey, sendTransaction } = useWallet();
const { publicKey } = useMoralis();
}
It looks as if {publicKey as pK} won't work and neither does {pK : publicKey}
What am I missing?
thanks

How do I load and run external Javascript code in React that have their definitions in the application and not in the imported file?

Basically, I'm trying to run a function that creates and adds a Recipe class to an array in React based on an external javascript file that is hosted online - but all the definitions are inside my React app.
The external file looks like (Recipes.js) this:
function LoadRecipes(){
AddToRecipes(new Recipe({
name: "Kronyxium Core",
components: [],
requirements: [],
craftedAt: "Frost Temple Smithy"
}));
}
The way I attempt to go on with this follows:
import React, {useState, useEffect} from 'react';
import RecipeManager from "../logic/RecipeManager.js";
const Recipe = RecipeManager.Recipe;
const recipesList = RecipeManager.recipesList;
const AddToRecipes = RecipeManager.AddToRecipes;
function RecipeController() {
const [loadingRecipes, setLoadingRecipes] = useState(true);
useEffect(() => {
const script = document.createElement("script");
script.src = "https://raw.githack.com/Soralei/extern/main/Recipes.js";
script.async = true;
script.onload = () => {
setLoadingRecipes(false);
}
document.body.appendChild(script);
}, []);
useEffect(() => {
if(!loadingRecipes){
window.LoadRecipes();
}
}, [loadingRecipes]);
return (
<div>
{loadingRecipes ? <p>Loading recipes...</p> : (
<>
<p>Recipes:</p>
{/*recipesList.map((a, index) => <p key={"r"+index}>{a.name}</p>)*/}
</>
)}
</div>
)
}
export default RecipeController
Note that I try to run the function using window.LoadRecipes() once the script has been imported. However, I get undefined errors when the function is run:
Recipes.js:3 Uncaught ReferenceError: AddToRecipes is not defined
at LoadRecipes (Recipes.js:3)
I'm also adding the content of RecipeManager.js for clarity. This is local logic, and the goal is to have the external function make use of it:
class Recipe{
constructor(options = {}){
this.name = options.name || "Unnamed Recipe";
this.components = options.components || [];
this.requirements = options.requirements || [];
this.craftedAt = options.craftedAt || "handcrafted";
}
}
const recipesList = [];
function AddToRecipes(Recipe){
recipesList.push(Recipe);
console.log(Recipe.name, "was added to the recipes list.");
}
const exported = {
Recipe: Recipe,
recipesList: recipesList,
AddToRecipes: AddToRecipes
}
export default exported;
Is this not possible, or am I just doing this entirely wrong?
Why am I doing this? The idea is to host the recipes online in a way that allows for other people to easily view, edit, and have the changes affect my app directly, while keeping most of the work in the React app.
You have to export the function to be able to access it.
Default export (only one per file):
function LoadRecipes(){
AddToRecipes(new Recipe({
name: "Kronyxium Core",
components: [],
requirements: [],
craftedAt: "Frost Temple Smithy"
}));
}
export default LoadRecipes; // export
You should import it like this:
import LoadRecipes from 'pathtofile';
Named export (multiple ones):
export function LoadRecipes() {
AddToRecipes(new Recipe({
name: "Kronyxium Core",
components: [],
requirements: [],
craftedAt: "Frost Temple Smithy"
}));
}
export const add (a, b) => a + b; // another one
Import like this (using { }):
import {
LoadRecipes,
add
} from 'pathtofile';
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value. Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the “main” exported value since it will be the simplest to import.
You can read about JavaScript modules here

How can I Use Consts from different files in React JS

Can you please tell me how to use consts from different JS files in React. I'm trying to calculate a total score of 4 different Quiz scores (Average).
Thank you !
I did try to export and import but didn't work.
Here is the code I'm working on for the first quiz :
const playerStatsEco = {
ecoscore: null,
numberOfQuestions: null,
numberOfAnsweredQuestions: null,
correctAnswers: null,
wrongAnswers: null,
};
class playeco extends Component {
...
endGame = () => {
alert('Le quiz est terminé ! لقد انتهى الاختبار');
const { state } = this;
playerStatsEco.ecoscore = state.ecoscore;
playerStatsEco.numberOfQuestions = state.numberOfQuestions;
playerStatsEco.numberOfAnsweredQuestions = state.correctAnswers + state.wrongAnswers;
playerStatsEco.correctAnswers = state.correctAnswers;
playerStatsEco.wrongAnswers = state.wrongAnswers;
setTimeout(() => {
this.props.history.push('/play/sum', playerStatsEco);
}, 1000);
};
When I try to export the class, it works. But when I try to export the const as well using this line
export {playeco, playerStatsEco};
This error happens :
Attempted import error: './components/quiz/playeco' does not contain a default export (imported as 'playeco').
You can export your consts and import them from different files.
// In file where constant declared
export const myConst = "some value";
//In imported file
import {myConst} from "./fileWhereConstDeclared"
You can export them:
export const playerStatsEco = {...}
export class playeco extends Component {...}
then you can import them from outside like that :
import {playerStatsEco, playeco } from "./fileWhereConstDeclared"

TypeError: Webpack imported module is not a function

I have a backend that calculates work shifts.
I am trying to post some required user input with a module in services/shifts.
The getAll method works fine, but posting throws an error
TypeError: _services_shifts__WEBPACK_IMPORTED_MODULE_2__.default.postData is not a function
Shiftservice module:
import axios from 'axios'
const baseUrl = '...'
const getAll = () => {
const request = axios.get(baseUrl)
return request.then(response => response.data)
}
const postData = newObject => {
const request = axios.post(baseUrl, newObject)
return request.then(response => response.data)
}
export default {getAll, postData}
I have a button that triggers the following calling code on click:
import shiftService from './services/shifts'
const postData = (event) => {
event.preventDefault()
const sampleObject = {
sampleField: sample
}
shiftService
.postData(sampleObject)
.then(returnedData => {
console.log(returnedData)
})
}
When execution reaches shiftService.postData, the error is thrown.
I am really confused since I am basically copying some older project of mine which works, but here I just don't find the problem. Thank you in advance for helping a newcomer!
Modules provide special export default (“the default export”) syntax to make the “one thing per module” way look better.There may be only one export default per file.And we may neglect the name of the class in the following example.
//Module1
export default class{
}
And then import it without curly braces with any name:
//Module2
import anyname from './Module1'
Your scenario is different having two functions.You can either export default one function
export default getAll
and normal export the other function.
export postData
and when importing
import{ default as getAll,postData} from './yourModule'
OR
Remove default here in Shiftservice module and export normally:
import axios from 'axios'
const baseUrl = '...'
const getAll = () => {
const request = axios.get(baseUrl)
return request.then(response => response.data)
}
const postData = newObject => {
const request = axios.post(baseUrl, newObject)
return request.then(response => response.data)
}
export {getAll, postData}
Importing in your module
import {getAll,PostData} from './Module1'
or
import * as shiftService from './Module1'
and then use shiftServer.postData().....
Okay, I am embarrassed of the solution. I was just editing an earlier version of shiftService from a wrong folder, and the imported service only had the get method in it...
So my code actually works if placed correctly. Thank you for your time, and thanks for sharing alternative ways that must work aswell.
I think its becuse your declaring the function as arrow functions
and export it this way:
export default {getAll, postData}
you need to declare them as a normal functions
function postData(){
}
that should work

How can I export all functions from a file in JS?

I'm creating a unit converter, and I want to put all of the conversion functions into their own file. Using ES6 export, is there any way to export all of the functions in the file with their default names using only one line? For example:
export default all;
The functions are all just in the file, not within an object.
No, there's no wildcard export (except when you're re-exporting everything from another module, but that's not what you're asking about).
Simply put export in front of each function declaration you want exported, e.g.
export function foo() {
// ...
}
export function bar() {
// ...
}
...or of course, if you're using function expressions:
export var foo = function() {
// ...
};
export let bar = () => {
// ...
};
export const baz = value => {
// ...
};
I think there are a lot of solutions to this. And as has been answered, there's no wildcard export. But, you can 'wildcard' the import. So, I much prefer the one putting export before each of the functions you want to expose from the file:
//myfile.js
export function fn1() {...}
export function fn2() {...}
and then import it like so:
import * as MyFn from './myfile.js'
Afterwards you could use it like so:
MyFn.fn1();
MyFn.fn2();
You can also use module.exports as follows:
function myFunction(arg) {
console.debug(arg);
}
function otherFunction(arg) {
console.error(arg);
}
module.exports = {
myFunction: myFunction,
otherFunction: otherFunction,
};
Then you can import it:
import {myFunction, otherFunction} from "./Functions.js";
In my use case, I do have three reusable functions in one file.
utils/reusables.js
export const a = () => {}
export const b = () => {}
export const c = () => {}
In order to point the root folder instead of individual file names, I created a file called index.js which will comprise of all the functions that are listed in individual files.
utils/index.js
export * from './reusables'
Now, when I want to use my a function, I will have to simply import it like this
import { a } from '../utils'
Rather than calling it from its individual files
import { a } from '../utils/reusables'
You could also export them at the bottom of your script.
function cube(x) {
return x * x * x;
}
const foo = Math.PI + Math.SQRT2;
var graph = {
options: {
color:'white',
thickness:'2px'
},
draw: function() {
console.log('From graph draw function');
}
}
export { cube, foo, graph };
You can also aggregate submodules together in a parent module so that they are available to import from that module.
// In parentModule.js
export { myFunction, myVariable } from 'childModule1.js';
export { myClass } from 'childModule2.js';
// In top-level module
import { myFunction, myVariable, myClass } from 'parentModule.js'
For Node.js environment, what I did to export functions was this.
UserController.js
module.exports = {
signUp: () => {
return "user"
},
login: () => {
return "login"
}
}
UserRouter.js
const UserController = require('./UserController')
then login and signUp functions could be used inside UserRouter as UserController.signUp() and UserController.login()
I think there's a missing common solution, which is exporting in index.js file:
myModule/myFunctions.js
export const foo = () => { ... }
export const bar = () => { ... }
then in myModule/index.js
export * from "./myFunctions.js";
This way you can simply import and use it with:
import { foo, bar } from "myModule";
foo();
bar();
functions.js
function alpha(msj) {
console.log('In alpha: ' + msj);
}
function beta(msj) {
console.log('In beta: ' + msj);
}
module.exports = {
alpha,
beta
};
main.js
const functions = require('./functions');
functions.alpha('Hi');
functions.beta('Hello');
Run
node main.js
Output
In alpha: Hi
In beta: Hello
In case anyone still needs an answer to this in modern JavaScript:
const hello = () => "hello there"
const bye = () => "bye bye"
export default { hello, bye }
What I like to do is to export all functions within an object:
//File.js
export default {
testFunction1: function testFunction1(){
console.log("Hello World")
},
//a little bit cleaner
testFunction2: () => {
console.log("Nothing here")
}
}
Now you can access the functions with calling the key value of the object:
//differentFile.js
import file from 'File.js'
file.testFunction1()
//Hello World
file.testFunction2()
//Nothing here

Categories

Resources