Can't access to variable inside a function arguments call [duplicate] - javascript

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 } } })

Related

Although I am using Duplicate array, Array.map() function changing my original array [duplicate]

This question already has answers here:
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 1 year ago.
I have an array like :
export const switches = [
{ id: 1, switchName: 'HS - 3015', operation: 'Auto Start GA-3001 S', isActive: true },
{ id: 2, switchName: 'HS - 3016', operation: 'FSLL - 3001 (Pass - 1)', isActive: false },
{ id: 3, switchName: 'HS - 3017', operation: 'FSLL - 3002 (Pass - 2)', isActive: true }
];
In my component I added a additional property value which is boolean and which is used for control switch.
In a function I first duplicate this array and than modify this duplicate array that is value: true/false to value: 'normal/bypass'. The big issue is I am not getting my original array. I am always get the modified array.
What is the problem, I can't figure out.
Switch change and Submit function like this:
const onSwitchChange = (e, switchId) => {
const { checked } = e.target;
const oldState = [...state];
const updatedState = oldState.map(s => {
if (s.id === switchId) {
s['value'] = checked;
}
return s;
});
setState(updatedState);
};
const onSubmit = () => {
const oldData = [...state];
const data = oldData.map(item => {
item.value = item.value === true ? 'Bypass' : 'Normal';
return item;
});
document.getElementById('jsonData').textContent = JSON.stringify(data, null, 2);
};
Find in codesandbox: https://codesandbox.io/s/switch-control-4ovyk
the map function will always return a new array with elements that are the result of a callback function.
In your case, the map function should return a new array with the value changed to Bypass or Normal and it will be stored in the constant data.
However, you can still access your original array by calling oldData

spread operator in javascript with key in array [duplicate]

This question already has an answer here:
Dynamic object property names?
(1 answer)
Closed 1 year ago.
Going over this code in github https://github.com/WebDevSimplified/postman-clone, I simply do not understand below portion
function keyValuePairsToObjects(container) {
const pairs = container.querySelectorAll('[data-key-value-pair]')
return [...pairs].reduce((data, pair) => {
const key = pair.querySelector('[data-key]').value
const value = pair.querySelector('[data-value]').value
if (key === '') return data
return { ...data, [key]: value }
}, {})
}
{...data, [key]: value} Why is key inside of an array?
Key is not an array, this is the syntax for using a variable name as the key, like the obj["prop"] syntax, { ["prop"]: true } is like { prop: true }.
Context for comments:
> { ["prop"]: true }
{ prop: true }
> { prop: true }
{ prop: true }

How to pass index of an array without hardcoding to update method of 'react-addons-update'? [duplicate]

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 } } }),
});

Updating object in array with Vuex [duplicate]

This question already has answers here:
Update data using vuex
(4 answers)
Closed 4 years ago.
How can I update an object inside an array with Vuex? I tried this, but it didn't work:
const state = {
categories: []
};
// mutations:
[mutationType.UPDATE_CATEGORY] (state, id, category) {
const record = state.categories.find(element => element.id === id);
state.categories[record] = category;
}
// actions:
updateCategory({commit}, id, category) {
categoriesApi.updateCategory(id, category).then((response) => {
commit(mutationType.UPDATE_CATEGORY, id, response);
router.push({name: 'categories'});
})
}
[mutationType.UPDATE_CATEGORY] (state, id, category) {
state.categories = [
...state.categories.filter(element => element.id !== id),
category
]
}
This works by replacing the 'categories' array with the original array without the matching element, and then concatenating the updated element to the end of the array.
One caveat to this method is that it destroys the order of the array, although in a lot of cases that won't be a problem. Just something to keep in mind.

check value is object when updating state [duplicate]

This question already has answers here:
Finding Variable Type in JavaScript
(12 answers)
Closed 5 years ago.
I am sending the following data to my reducer:
const data = {
value: { age, gender, ethnicity },
field: 'accessCode',
actionType: 'ADD_DETAILS',
};
this.props.dispatch(formHandler(data));
How can I check to see if the value prop is a single value, or an object with three values?
My action:
export function formHandler(data) {
return function(dispatch) {
// check data.value is an object with three value
if (..) {
this.props.dispatch(
showError({
type: 'SHOW_MODAL',
modalType: 'SHOW_ERROR',
})
);
} else {
dispatch({
type: data.actionType,
field: data.field,
value: data.value,
});
}
};
}
My reducer to update state:
switch (action.type) {
case ADD_LANGUAGE:
case ADD_ACCESSCODE:
case ADD_ACCESSCODE:
case ADD_DRINKS_CONCERN:
return {
...state,
[action.field]: action.value,
};
case ADD_DETAILS:
return {
...state,
...action.value,
};
Concerning the comment of how to check, this could be a start.
if (typeof(data.value) === 'object' && Object.keys(data.value).length === 3)
I'm not exactly sure how specific your needs are (does it need to be exactly 3 keys for example), but feel free to expand and I can chime in.
If you are okay using the Object prototype, you can test using this:
Object.getOwnPropertyNames(data).length
Object.getOwnPropertyNames returns an array with all property values with a length property of it's own included.

Categories