How to delete multiple url params - javascript

There is a problem with deleting several string parameters. Only the last parameter is being deleted now.
upd: I did not specify that I wanted to achieve the ability to remove specific parameter values
this code does not work correctly:
const updateFiltersSearchParams = (paramKey, newValue) => {
const isParamExist = searchParams.getAll(paramKey).includes(newValue);
if (!isParamExist) {
searchParams.append(paramKey, newValue);
setSearchParams(searchParams);
} else {
const updatedSearchParams = new URLSearchParams(
[...searchParams].filter(
([key, value]) => key !== paramKey || value !== newValue
)
);
setSearchParams(updatedSearchParams);
}
};
const handleDeleteParams = () => {
[...checkboxParams].forEach((param) => {
updateFiltersSearchParams("selected", param);
});
};
Sandbox

change your handleDeleteParams function with this
const handleDeleteParams = () => {
setSearchParams([]);
};

If you want to delete *only the selected (or any specific queryString key) queryString parameters you can use the delete method of the URLSearchParams object, then enqueue the params URL update.
const handleDeleteParams = (key) => {
searchParams.delete(key);
setSearchParams(searchParams);
};
...
<button type="button" onClick={() => handleDeleteParams("selected")}>
Clear all "selected" params
</button>

Solved the problem by modifying the function like this
const toggleSearchParams = (params) => {
const newSearchParams = [...searchParams];
for (const prevParam of params) {
const index = newSearchParams.findIndex(
(newParam) =>
prevParam[0] === newParam[0] && prevParam[1] === newParam[1]
);
if (index === -1) {
newSearchParams.push(prevParam);
} else {
newSearchParams.splice(index, 1);
}
}
setSearchParams(new URLSearchParams(newSearchParams));
};
const handleChangeCheckBoxValue = (e) => {
toggleSearchParams([["selected", e.target.value]]);
};
const handleDeleteParams = () => {
toggleSearchParams(checkboxParams.map((param) => ["selected", param]));
};

Related

how to access a variable outside onClick function react

I'm trying to get list from the onClick function but I can't if there any solution, please.
here is my full code link
let abe = []
const click = (e) => {
const cityy = e.target.value
const checkUsername = obj => obj.city === cityy;
const result = abe.some(checkUsername)
if (!result) {
abe.push({ "city": cityy})
}
if (!e.target.checked) {
const indexe = abe.findIndex(p => p.city === cityy)
abe.splice(indexe, 1)
}
const simo = watch("simo")
let list = abe.map((list) => list.city).join(" , ")
}
Is the click function triggered in the first place? You have actually missed to show where the click function is used.
Here is an example. Looks like you have to store cities in the state.
const [citiesList, setCitiesList] = useState<string[]>([]);
const click = (e) => {
const cityy = e.target.value
const checkUsername = obj => obj.city === cityy;
const result = citiesList.some(checkUsername)
if (!result) {
setCitiesList(prevState => [...prevState, cityy]);
}
if (!e.target.checked) {
const cList = [...citiesList];
const indexe = cList.findIndex(p => p === cityy)
cList.splice(indexe, 1);
setCitiesList(cList);
}
const simo = watch("simo");
}

Dynamically build external API URL and parameters

Today we have an object to keep track an external API usage like this:
const setParams =
(params) => Object.keys(params).map(
(element) => element + '=' + encodeURIComponent(params[element])).join('&')
const API = {
Common: {
Search: (order) => `Common/Search?${setParams({order})}`,
}}
console.log(API.Common.Search(1)); // "Common/Search?order=1"
However, we still get some typos what could be avoided.
Is it possible to dynamically set that URL even what we would need to change that API structure a bit?
const API = {
Common: {
Search: (order) => `${magicParent}/${magicCurrent}?${params}`,
Another: (login, argA, argB) => `${magicParent}/${magicCurrent}?${magic(params)}`,
}}
console.log(API.Common.Search(1)); // "Common/Search?order=1"
console.log(API.Common.Another(1,2,3)); // "Common/Another?login=1&argA=2&argB=3"
Thanks,
Just an idea | Not tested | Ugly (mutates):
const isObject = // Implement yourself
const injectPath = (obj, path = '') => {
Object.entries(obj).forEach( ([key, value]) => {
if (isObject(value) {
injectPath(value, path + '/' + key;
} else {
// It is a function
obj[key] = value(path);
}
})
}
const API = injectPath({
Common: {
Search: (path) => (order) => `${path}?${setParams({order})}`,
}}
});

How can i modifier a state only when has the same ID

editItem = (id) => {
this.setState(
{
lanche: [
{
id: id,
editItem: true
}]
}
)
}
In this way, setState runs on all items in the array, I need to edit only the item that has the same ID
You need to find the item in the array with the given id, and modify that one only. setState method changes the whole object with the given key.
try this:
editItem = (id) => {
this.setState(
{
lanche: this.state.lanche.map(item => {
if(item.id === id) {
item.editItem = true
}
return item;
})
}
)
}
You can use map like this:
editItem = (id) => {
// update the relevant item
const updatedItems = this.state.lanche.map(item => {
if (item.id === id) {
item.editItem = true;
}
return item;
} );
this.setState(
{
lanche: updatedItems
}
)
}
If I understand your question;
You could search for the index like so;
const index = this.state.lanche.findIndex((e) => e.id === id);
and then alter the object
const newLanche = this.state.lanche;
newLanche[index].editItem = true;
And then update the store;
this.setState({ lanche: newLanche });

Modifying an array of objects with uuid keys

I've got add
I've got delete
now I need modify
add just adds to the pile haphazardly
delete is able to do it's work with surgical precision because it uses key to find it's culprit :
addInput = (name) => {
const newInputs = this.props.parameters;
newInputs.push({
name,
key: uuid(),
value: { input: '' },
icon: { inputIcon: 0 },
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
removeInput = (key) => {
const newInputs = this.props.parameters.filter(x => x.key !== key);
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
how do I modify (for example set the value back to '' without deleting and recreating the item) ?
modifyInput = (key) => {
?????
};
You can use Array.prototype.find()
modifyInput = (key) => {
const match = this.props.parameters.find(x => x.key === key);
// do stuff with matched object
};
You can map through the parameters and then modify when you find a match:
modifyInput = (key) => {
const newInputs = this.props.parameters.map(x => {
if (x.key === key) {
x.modification = true;
}
return x;
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
var empMap= {};
//initialize empMap with key as Employee ID and value as Employee attributes:
//Now when salary updated on UI from 100 - 300 you can update other fields
var e=empMap[id];
if(e){
e.Salary=newSalary;
e.YearlySalary = newSalary*12;
e.Deductions = e.YearlySalary*0.2;
empMap[id]=e;
}

Update elements of array of object when one element is changed [duplicate]

I've got add
I've got delete
now I need modify
add just adds to the pile haphazardly
delete is able to do it's work with surgical precision because it uses key to find it's culprit :
addInput = (name) => {
const newInputs = this.props.parameters;
newInputs.push({
name,
key: uuid(),
value: { input: '' },
icon: { inputIcon: 0 },
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
removeInput = (key) => {
const newInputs = this.props.parameters.filter(x => x.key !== key);
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
how do I modify (for example set the value back to '' without deleting and recreating the item) ?
modifyInput = (key) => {
?????
};
You can use Array.prototype.find()
modifyInput = (key) => {
const match = this.props.parameters.find(x => x.key === key);
// do stuff with matched object
};
You can map through the parameters and then modify when you find a match:
modifyInput = (key) => {
const newInputs = this.props.parameters.map(x => {
if (x.key === key) {
x.modification = true;
}
return x;
});
this.setState({
newInput: newInputs,
});
this.props.exportParameter(newInputs);
};
var empMap= {};
//initialize empMap with key as Employee ID and value as Employee attributes:
//Now when salary updated on UI from 100 - 300 you can update other fields
var e=empMap[id];
if(e){
e.Salary=newSalary;
e.YearlySalary = newSalary*12;
e.Deductions = e.YearlySalary*0.2;
empMap[id]=e;
}

Categories

Resources