This question already has answers here:
Destructuring deep properties
(4 answers)
Closed 3 years ago.
I am using Firebase with React, and using a Firebase File uploader and I'm using a module that uses this syntax
const { target: { files } } = event;
What does that do?
Below is the full code
I tried googling destructuring, but no luck, can someone confirm if it is ?
customOnChangeHandler = (event) => {
const { target: { files } } = event;
const filesToStore = [];
files.forEach(file => filesToStore.push(file));
this.setState({ files: filesToStore });
}
It is a destructuring assignment:
const { target: { files } } = event;
// equals to:
// const files = event.target.files;
This is es6 destructuring feature, it allows to destruct (pick) a field from an object.
Related
This question already has answers here:
How does technique for making a copy of a function works in JavaScript (Storybook example)
(2 answers)
Closed last month.
Going through the storybook documentation
essentially this part caught my eye:
const Template = (args) => ({
//👇 Your template goes here
});
export const Primary = Template.bind({});
So I got curious, what is the reason for calling bind on an arrow function? I tried it and the only effect I've seen is that it is hiding the function implementation from toString.
Primary.toString()
> 'function () { [native code] }'
It seems completely pointless at first, but it's a way to create a new function that does the same as the original one. In another example further down on that page, you can see
const Template = (args) => ({
//👇 Your template goes here
});
ArrayInclude = Template.bind({})
ArrayInclude.parameters = { controls: { include: ['foo', 'bar'] } };
RegexInclude = Template.bind({})
RegexInclude.parameters = { controls: { include: /^hello*/ } };
ArrayExclude = Template.bind({})
ArrayExclude.parameters = { controls: { exclude: ['foo', 'bar'] } };
RegexExclude = Template.bind({})
RegexExclude.parameters = { controls: { exclude: /^hello*/ } };
which creates multiple bound function objects from the same Template and assigns different .parameters to them.
The same could be achieved with
const Primary = Template.bind();
const Primary = Template.bind(null);
const Primary = (args) => Template(args);
// etc
This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 10 months ago.
I have the following function. The current output is name: "foo" surname: "bar"
How can I push my console log data to my payload
{
name: "foo",
surname: "bar
}
so the output becomes:
const ProcessHTML = (rawHtml, elements) => {
const $ = cheerio.load(rawHtml);
let payload = {}
for (const data in elements) {
let currentElement = $(elements[data]);
let prettify = pretty(currentElement.html())
console.log(`${data}: ${prettify}`)
}
return payload
};
I can't understand if you are trying to output a single value in console or the full payload object, but I think is something like that:
const ProcessHTML = (rawHtml, elements) => {
const $ = cheerio.load(rawHtml);
let payload = {}
elements.forEach( data => {
let prettify = pretty($(elements[data]).html());
payload = Object.assing(payload, { data:prettify });
console.log(`${data}: ${prettify}`)
})
return payload
};
If you need to output the entirely object, just change the console.log to console.log(payload)
My application is rather large, so to have a more organized translation file I want to use nasted namespaces. Example:
{
"contract": {
"index": {
"pageTitle": "Contract"
}
}
The problem with this is when I'm accessing it. With the help of this question I found out I can access the keys inside index by using it as below:
const { t, i18n } = useTranslation('contract', { useSuspense: false });
...
t('index.pageTitle')
The problem is It seems rather unecessary to prefix index. to every key I want to access. What I would like to do is import the namespace index instead of contract, and use it as below:
const { t, i18n } = useTranslation('contract:index', { useSuspense: false });
...
t('pageTitle')
Which doesn't work. I tried contract.index as well. In the official documentation I found nothing about nesting. Is it possible to accomplish what I'm trying to do or will I have to stick with prexifing every key?
Nested namespaces are not supported.
You can decorate the useTranslation hook to provide this extended functionality for pages in the namespace.
import { useTranslation as useTranslationBase } from "react-i18next";
const useTranslation = (ns, page, props={}) => {
const trans = useTranslationBase(ns, props);
return {
...trans,
t: (keys, options) => {
let _keys = keys;
if (!Array.isArray(keys)) _keys = [String(keys)];
_keys = _keys.map(key =>`${page}.${key}`)
return trans.t(_keys, options)
}
}
}
Usage
export default function () {
const { t } = useTranslation('contract', 'index');
return <div>{t(["pageTitle"])}-{t("pageTitle")}</div>
}
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 2 years ago.
case 'ADD_CHAT_MESSAGE':
const index = state.tasks.findIndex(elm => elm.userid === action.taskid)
const task = state.tasks
return update(
state, { tasks: { index: { $set: action.task } } })
I would like to use index inside update function but my IDE alerting me that index is declared nut never used.
Since index is dynamic, you must use [] with it, otherwise it will just be setting the index key
case 'ADD_CHAT_MESSAGE':
const index = state.tasks.findIndex(elm => elm.userid === action.taskid)
const task = state.tasks
return update(
state, { tasks: { [index]: { $set: action.task } } })
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Creating object with dynamic keys [duplicate]
(2 answers)
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed 4 years ago.
nameChangedHandler = (id, event) => {
let index = id;
const updatedName = event.target.value;
this.setState({
persons: update(this.state.persons, { index: { name: { $set: updatedName } } }),
});
};
If I hardcode the index to any number the above code is working i.e ( update(this.state.persons, { 0: { name: { $set: updatedName } } }) )
Kindly Suggest a Solution.
replace { index: ... } with { [index]: ... }
You can use a computed property to use the value of the index variable:
this.setState({
persons: update(this.state.persons, { [index]: { name: { $set: updatedName } } }),
});