I'm having this question, since const variables are not hoisted and a syntax error should be thrown.
Why does this code work?
export let testModule = () => {
let test = document.querySelector('.test');
test.innerHTML = myText;
test.style.cssText = 'color: red';
}
const myText = 'IT WORKS!!!!!'
I've attached the working plunk if you want to check for yourself: https://plnkr.co/edit/TR8SvCjQgqPDWpI3?preview
Why can I access const before declaration in exported module
Because testModule() isn't called until later and const myText is defined in a reachable scope by the time the function is called.
Related
In the Appwrite console, I'm adding a test environment variable to pass into function...
In my function code (NodeJs) index.js, I'm logging out the value of above variable...
I save the code and use the Appwrite CLI (createTag) to push/publish the code.
Then in Appwrite console, I activate the new function then I execute it and I see this in log...
Clearly I'm missing something but I'm searching the Appwrite docs and I don't see it.
What am I doing incorrectly?
Thank you for helping :-)
Ok looks like as of this post, this is a bug in the Appwrite web UI code. You can do this 2 ways right now. You can set the environment vars in code or you can use the Appwrite CLI. I ended up putting the CLI commend in my NodeJs package.json scripts for quick easy access.
Here are both ways that worked for me...
appwrite functions create --functionId=regions_get_all --name=regions_get_all --execute=[] --runtime=node-16.0 --vars={ 'LT_API_ENDPOINT': 'https://appwrite.league-tracker.com/v1', 'LT_PROJECT_ID': '61eb...7e4ff', 'LT_FUNCTIONS_SECRET': '3b4b478e5a5576c1...ef84ba44e5fc2261cb8a8b3bfee' }
const sdk = require('node-appwrite');
const endpoint = 'https://appwrite.league-tracker.com/v1';
const projectId = '61eb3...7e4ff';
const funcionsSecret = '3b4b478e5a557ab8a...c121ff21977a';
const functionId = process.argv[2];
const name = process.argv[2];
const execute = [];
const runtime = 'node-16.0';
const env_vars = {
"LT_API_ENDPOINT": endpoint,
"LT_PROJECT_ID": projectId,
"LT_FUNCTIONS_SECRET": funcionsSecret
};
// Init SDK
const client = new sdk.Client();
const functions = new sdk.Functions(client);
client
.setEndpoint(endpoint) // Your API Endpoint
.setProject(projectId) // Your project ID
.setKey('33facd6c0d792e...359362efbc35d06bfaa'); // Your secret API key
functions.get(functionId)
.then(
func => {
// Does this function already exist?
if ((typeof (func) == 'object' && func['$id'] == functionId)) {
throw `Function '${functionId}' already exists. Cannot 'create'.\n\n`;
}
// Create the function
functions.create(functionId, name, execute, runtime, env_vars)
.then(
response => console.log(response),
error => console.error(`>>> ERROR! ${error}`)
);
}).catch(
error => console.error(`>>> ERROR! ${error}`)
);
As of Appwrite 0.13.0, an Appwrite Function must expose a function that accepts a request and response. To return data, you would use the response object and either call response.json() or response.send(). The request object has an env object with all function variables. Here is an example NodeJS Function:
module.exports = async (req, res) => {
const payload =
req.payload ||
'No payload provided. Add custom data when executing function.';
const secretKey =
req.env.SECRET_KEY ||
'SECRET_KEY environment variable not found. You can set it in Function settings.';
const randomNumber = Math.random();
const trigger = req.env.APPWRITE_FUNCTION_TRIGGER;
res.json({
message: 'Hello from Appwrite!',
payload,
secretKey,
randomNumber,
trigger,
});
};
In the example above, you can see req.env.SECRET_KEY being referenced. For more information, refer to the Appwrite Functions docs.
Here is the code:
let args = {
"wz_nav_style": "dots", // dots, tabs, progress
"buttons": true,
"navigation": 'all' // buttons, nav, all
};
const wizard = new wizard(args);
wizard.init();
document.addEventListener("submitWizard", function (e) {
alert("Form Submit");
});
I get the error:
Block-scoped variable 'wizard' used before its declaration.ts(2448)
How to solve this?
The constant name wizard overshadows the reference of the constructor named as the same. Changing the constant name to something other than the constructor would solve the problem.
const wiz = new wizard(args);
wiz.init();
I've been making a discord.js bot following the official guide.
I have all my commands in the /commands folder as advised.
Then I followed the course to create a currency system with sequelize, following this page from the same guide.
I have a balance.js file inside the commands folder, but when I'm calling it, it gives me this error:
TypeError: currency.getBalance is not a function
I've defined the function in my app.js file, but how can I export it (or use it) inside the balance.js which is called by the app.js file?
This is the function defined in the main file app.js:
Reflect.defineProperty(currency, 'getBalance', {
value: function getBalance(id) {
const user = currency.get(id);
return user ? user.balance : 0;
},
});
This is balance.js:
module.exports = {
name: 'balance',
description: 'Informs you about your balance.',
cooldown : 10,
guildOnly : true,
aliases: ['bal', 'cur', 'gem', 'gems'],
execute(message, args) {
const Discord = require('discord.js');
const { Users, CurrencyShop, UserItems, CardBase, UserCollec } = require('../dbObjects');
const currency = require('../app.js')
async () => { const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
UserCollec.sync(); }
const target = message.author;
return message.channel.send(`${target} has ${currency.getBalance(target.id)}<:Gem:756059891465977886>`);
},
};
EDIT:
I progressed. Now I understand that I have to import the currency variable, which has been declared as a new Discord.Collection() in app.js.
I need to refer to this variable in a module and this module doesn't seem to see it as a collection. How do I import it?
So I am using the DraftJS package with React along with the mentions plugin. When a post is created, I store the raw JS in my PostreSQL JSONField:
convertToRaw(postEditorState.getCurrentContent())
When I edit the post, I set the editor state as follows:
let newEditorState = EditorState.createWithContent(convertFromRaw(post.richtext_content));
setEditorState(newEditorState);
The text gets set correctly, but none of the mentions are highlighted AND I can't add new mentions. Does anyone know how to fix this?
I am using the mention plugin: https://www.draft-js-plugins.com/plugin/mention
to save data
function saveContent() {
const content = editorState.getCurrentContent();
const rawObject = convertToRaw(content);
const draftRaw = JSON.stringify(rawObject); //<- save this to database
}
and retrieval:
setEditorState(()=> EditorState.push(
editorState,
convertFromRaw(JSON.parse(draftRaw)),
"remove-range"
););
it should preserve your data as saved.
the example provided (which works ok) is for inserting a new block with mention, saving the entityMap as well.
mentionData is jus a simple object {id:.., name:.., link:... , avatar:...}
One more thing:
initialize only once:
in other words do not recreate the state.
const [editorState, setEditorState] = useState(() => EditorState.createEmpty() );
und then populate something like:
useEffect(() => {
try {
if (theDraftRaw) {
let mtyState = EditorState.push(
editorState,
convertFromRaw(JSON.parse(theDraftRaw)),
"remove-range"
);
setEditorState(mtyState);
} else editorClear();
} catch (e) {
console.log(e);
// or some fallback to other field like text
}
}, [theDraftRaw]);
const editorClear = () => {
if (!editorState.getCurrentContent().hasText()) return;
let _editorState = EditorState.push(
editorState,
ContentState.createFromText("")
);
setEditorState(_editorState);
};
I am using Angular 6 and I am trying to load component dynamically by it's name
when user click on tab load component by name for this I am using the following code witch is working perfect on build but not work in build --production
loadTabData(tabname: any) {
this.selectedTab = tabname;
var factories = Array.from(this.resolver["_factories"].keys());
var factoryClass = <Type<any>>(
factories.find((x: any) => x.name === tabname)
);
let viewContainerRef = this.comLoad.viewContainerRef;
viewContainerRef.clear();
const factory = this.resolver.resolveComponentFactory(factoryClass);
let componentRef = viewContainerRef.createComponent(factory);
componentRef.instance.serviceId = this.serviceId;
}
when user click on tab I load the related component in production its return the following error
ERROR Error: No component factory found for undefined. Did you add it
to #NgModule.entryComponents?
at Wt (main.b98d71b6b5a909371223.js:1)
at e.resolveComponentFactory (main.b98d71b6b5a909371223.js:1)
Actually, this works fine in development and build since angular compiler not changing the name of component. in this line
var factories = Array.from(this.resolver["_factories"].keys());
var factoryClass = <Type<any>>(
factories.find((x: any) => x.name === tabname)
);
you are searching for component by it's name but in production this name changed you can detect this by print the factories
instead of you can search by component selector like this;
const factories = Array.from(this.resolver["_factories"].values());
const factory: any = factories.find(
(x: any) => x.selector === this.selector
);
selector not changed on productions
Hope this help you