How to update to an array if element already exists - arrays

I'm making a React-Native application. Thanks to everyone's help I could somehow make that work except for toggling YES and NO. Once the user clicks on a button I just want to check if that clicked item data already exists in the state, if so I want to update it. If it does not exist then it should be added to the state as a new Item.
I already coded the above logic, my code is working, but not returning correct output, elements are not adding or updating to the state array properly. How do I fix this code?
I want to generate output like this
[{
chelistid:231,
validiary : "YES",
remark : "Hello"
},{
chelistid:232,
validiary : "NO",
remark : "asddddd"
}]
My code
const [reqData, setReqData] = useState([]);
//Modify yes clicked
const yesClicked = (element) => {
let req = {
"chelistid": element.chelistid,
"validiary": "Yes",
"remark": element.remark
}
createCheckList(req);
}
//Modify no clicked
const noClicked = (element) => {
let req = {
"chelistid": element.chelistid,
"validiary": "No",
"remark": element.remark
}
createCheckList(req);
}
const createCheckList = (data) => {
const index = reqData.findIndex(x => x.chelistid === data.chelistid)
var modifiedArray = reqData
if (index !== -1) {
//Remove the element from the array
modifiedArray.splice(index, 1);
}
setReqData([modifiedArray, data]);
}

The problem is it seems like you are not spreading the array to append the data element. What you are doing by [modifiedArray, data] you are creating an array that contains an array and data something like [[modified array content here], data]. But actually, you want to append to modified array instead. For that, you need to expand the modified array by using ... which is called spread syntax. (Learn here) So, your code would look like:
setReqData([...modifiedArray, data]);

Related

Is this a React prevState issue and how can I solve it?

This is kind of complicated to explain. I'm trying to make a toggle function that adds and deletes items on a different page with useContext. Everything adds and deletes fine until I tab to the other page, and that's where the error begins. Once I do that the function ignores what's in the array and will duplicate items in the array. What's odd about it is if I console.log or manually check the new item with the current array items it shows me everything. For example in order to add the new item to the array it checks if the index of new item is -1. If it is it will add the item and if not it will delete the item. However once I leave the page it doesn't see the item anymore and adds it anyway. If I console.log the item name and new item name, I can see both, and if I use === to check it also works fine until I switch tabs and then even though it's still console logging both names somehow it's still adding the item and ignoring that it already contains the item.
The code directory in my sandbox is src/Helpers/MyPicsContext. Here is the link to my sandbox codesandbox
The tabs on the website are Picks and the search page which you can access on Picks before any items are added or by clicking the magnifying glass in the top right of page.
And here is the actual code for the context page.
export const MyPicksContextProvider = props => {
const [picksList, setPicksList] = useState(
JSON.parse(localStorage.getItem('picksList'))
||
[]
)
//console.log(picksList)
useEffect(() => {
localStorage.setItem("picksList", JSON.stringify(picksList));
}, [picksList]);
const deleteCoin = coin => {
if (picksList.length === 1) {
setPicksList([]);
} else {
setPicksList(picksList.filter(list => {
console.log(list)
//console.log(coin)
return list !== coin;
}))
}
console.log('deleted');
console.log(picksList)
}
const toggleCoin = (coin) => {
if (picksList.length === 0) {
setPicksList([...picksList, coin]);
} else {
if (picksList.indexOf(coin) === -1 ) {
setPicksList([...picksList, coin]);
console.log('added 1')
} else {
deleteCoin(coin)
}
}
}
Perhaps I just don't understand useState and prevState, but I can't seem to find any examples that apply to what I'm trying to do here. It makes total sense in creating a counter or something simple like that.
The issue is that .indexOf checks for referential equality of items, same as using ===. This means that const a = {id: 'x'}; const b = a; console.log(a === b); will output true, but const a = {id: 'x'}; const b = {id: 'x'}; console.log(a === b); will output false.
In your situation, upon changing pages / refreshing, the state is reset and loaded from local storage. However, this creates new objects which are not referentially equal. Instead of using .indexOf you want to use .find, something like array.find((element) => element.id === newItem.id) to find the index of the item. You could also do your own deep equality check (confirming every field matches), but I suspect the ID alone is sufficient.
In fact, I would also recommend only keeping the array of "picks" as an array of string ID's. Then you can lookup the full data from your table for each of these ID's. Otherwise the current price will be stored in localStorage, and could be out of date.

React Native - useState hook to update array within an object of arrays

How do I use useState hook to update an array within an array of objects that's dependent on an array index?
end goal data:
foodData = [
{
foodId: 'fdsafsdafsa',
fruitsArray: ['banana', 'orange']
},
{
foodId: '234243fdsfdsafsasdf343432afsdafsa',
fruitsArray: ['apple']
},
{
foodId: 'fdsafsdafsa',
fruitsArray: ['strawberry', 'orange']
},
]
I have a function with arguments, (fruits, fruitIndex, foodIndex, foodId)
const logFruitsIntoFoodData = (fruits, fruitIndex, foodIndex, foodId) => {
// update state here...
const foodToUpdate = {...foodData};
foodToUpdate[foodIndex] = {
...foodData[foodIndex],
// This gets overwritten,
// how do I continue to add or
// update the fruit based on fruit index?
['fruitsArray']: fruits,
};
}
I'm trying to update/add fruits into the fruitsArray so when the function gets invoked, it'll insert the proper fruits into foodData, or it'll update it, depending on what the fruitIndex is.
Should I be using two separate useState:
const [foodData, setFoodData]= useState([]);
const [fruitsArray, setFruitsArray] = useState([]);
where I should get the array of fruits first, then add it into foodData, or can I just have 1 useState to deal with everything?
I'm not sure I'd use an array, since you have foodId, meaning you could easily convert foodData into an object. I'd say if you're using an array then use the index. If you want to use foodId to identify the item you're updating, then just make foodData an object.
It's a little bit cumbersome but this is what I think you're trying to do:
const logFruitsIntoFoodData = (fruit, fruitIndex, foodIndex) => {
// isolate the food you're updating and clone it
const foodToUpdate = { ...foodData[foodIndex] };
// replace fruit in the specified index...
foodToUpdate.fruitsArray.splice(fruitIndex, 1, fruit);
// clone existing state
const newFoodDataState = [...foodData];
// replace the item in the specified
newFoodDataState.splice(foodIndex, 1, foodToUpdate);
// set new state
setFoodData(newFoodDataState);
};
I'm not 100% sure this is what you meant. Let me know and I can modify accordingly!
I was able to get it to work when I did it like this:
const [foodData, setFoodData]= useState([]);
const logFruitsIntoFoodData = (fruits, fruitIndex, foodIndex, foodId) => {
// checks if the index exists in the array.
if (!foodData[foodIndex]) {
foodData[foodIndex] = {
foodId,
fruitsArray: [],
};
setFoodData({...foodData});
}
// now I can insert fruits depending on the fruitIndex
foodId[foodIndex].fruitsArray[fruitIndex] = fruits;
}
Not sure if this is the best method, but it works. If anyone has a better way, I'd love to hear it!

React Push One State Array into Another

In essence, I have this working, I am building out a game component to allow users to select items they want to purchase, they get pushed into a pending array and then when they wish to check out I am pushing those objects from the pending array into the purchased array.
But something very odd is happening after that, the arrays look like it worked properly the pending array is empty and the purchased array has the correct items within it. The problem comes once I try and click a new item to put into the pending array if its the same item that is in the purchased array it alters the counter there.
I have been toying with different ways to try and fix this, but have no idea how it's affecting the purchased array without me setting the state again.
This is my code so far for operating this vendor functionality.
handleMerchantEquipment(item) {
let pending = this.state.merchantPending;
let found = Equipment.find(el => item === el.Name);
let check = pending.find(el => el.Name === found.Name);
if (!check) {
pending.push(found);
}
else {
var foundIndex = pending.findIndex(el => el.Name === check.Name);
check.Count +=1;
pending[foundIndex] = check;
}
let CP = [0];
let SP = [0];
let GP = [0];
let PP = [0];
pending.map(item => {
let cost = item.Cost * item.Count;
if (item.Currency === "CP") {
CP.push(cost);
}
else if (item.Currency === "SP") {
SP.push(cost);
}
else if (item.Currency === "GP") {
GP.push(cost);
}
else if (item.Currency === "PP") {
PP.push(cost);
}
});
let purchased = [];
this.state.merchantPending.map(item => {
purchased.push(item)
});
this.setState({
yourCP: totalCP,
yourSP: totalSP,
yourEP: totalEP,
yourGP: totalGP,
yourPP: totalPP,
purchased: purchased,
merchantPending: [],
});
Some of the code is related to the currency exchange which his working fine.
I have also tried the ... to update the array but the issue persisted with it updating the Count in the purchased state.
You are mutating state. You should not mutate state in React. You should always immutably change state in React.
I think the problem lies in this line.
let pending = this.state.merchantPending;
Change it to
let pending = [...this.state.merchantPending.map(obj => ({...obj}))];
Also, if you want to iterate an array, use forEach instead of map. map returns you a new array.
pending.forEach(item => {
...
}
What is that you want the purchasedArray to do when it encounters a duplicate entry or item? May you clarify that in your question?
If you want it to not allow duplicate items you have to first check the array to see if it contains that item. Pseudo code
if(contains) {
render alert
//or do something else
} else {
purchased.push(item)
}
I am not able to comment so I will delete this when you clarify.

React, dynamically add text to ref span

I'm trying to render a message to a span tag specific to an item in a list. I've read a lot about React 'refs', but can't figure out how to populate the span with the message after it's been referenced.
So there's a list of items and each item row has their own button which triggers an API with the id associated with that item. Depending on the API response, i want to update the span tag with the response message, but only for that item
When the list is created the items are looped thru and each item includes this
<span ref={'msg' + data.id}></span><Button onClick={() => this.handleResend(data.id)}>Resend Email</Button>
After the API call, I want to reference the specific span and render the correct message inside of it. But I can't figure out how to render to the span at this point of the code. I know this doesn't work, but it's essentially what I am trying to do. Any ideas?
if (response.status === 200) {
this.refs['msg' + id] = "Email sent";
I recommand using state. because string refs legacy (https://reactjs.org/docs/refs-and-the-dom.html#legacy-api-string-refs)
const msgs = [
{ id:1, send:false },
{ id:2, send:false },
{ id:3, send:false },
];
this.state = {
msgs
};
return this.state.msgs.map((msg, index) => {
const status = msg.send ? "Email Sent" : "";
<span>{ status }</span><Button onClick={() => this.handleResend(index)}>Resend Email</Button>
});
async handleResend (index) {
const response = await callAPI(...);
if(reponse.status !== 200) return;
const newMsgs = _.cloneDeep(this.state.msgs);
newMsgs[index].send = true;
this.setState({
msgs: newMsgs
})
}
The workaround is set innerText
this.refs['msg' + id].innerText = "Email sent";
But rather than using ref try to use state to update elements inside render.
i was facing with this issue right now and i figured it out this way:
// currentQuestion is a dynamic Object that comes from somewhere and type is a value
const _target = `${currentQuestion.type}_01`
const _val = this[`${_target}`].current.clientHeight // here is the magic
please note that we don't use . after this to call the ref and not using refs to achieve what we want.
i just guessed that this should be an Object that would hold inner variables of the current object. then since ref is inside of that object then we should be able to call it using dynamic values like above...
i can say that it worked automagically!

Array.filter() in Angular 2 Component

In one component I can filter my array using the following:
// Array of product objects
const result = products.filter(p => p.name.includes('val'));
and value of products remains same as the first value but filtered value stores in result.
But in the following code, filter() filters array of strings itself:
// Array of strings
const result = strs.filter(s => s.includes('val'));
The question is how can I filter strings and return result without modifying the strs itself?
Note: I tried with array.filter(function() { return res; }); but didn't make any change.
It returns the filtered ones and don't change the actual array. You are doing something wrong
const strs = ['valval', 'bal', 'gal', 'dalval'];
const result = strs.filter(s => s.includes('val'));
console.log(strs);
console.log(result);
First thing we need to know is, if we filter our list we loose our original data
products: any[] = [
{
"productId": 1,
"productName": "foo-bar",
"price": 32.99
}
]
and can't get it back without re-getting the data from it's source so we have to make another list to store the filtered list.
filteredProduce: any[];
Next if you are working to show a list of filtered product on a grid or something like this we need a way to know when the user changes the filter criteria. we could use event binding and watch for key presses or value changes, but an easier way is to change our _listFilter property into a getter and setter, like this
get listFilter: string {
return this._listFilter;
}
set listFilter(value:string) {
this._listFilter= value;
}
next we want to set our filteredProducts array to the filtered list of products like this
set listFilter(value:string) {
this._listFilter= value;
this.filteredProducts = this._listFilter? this.performFilter(this._listFilter) : this.products;
}
in preceding code we are using js conditional operator to handle the posibility that _listFilterstring is empty, null or undefined.
Next we use this.performFilter(this._listFilter) to filter our list.
performFilter(filterBy: string): any[] {
filterBy = filterBy.toLocaleLowerCase();
return this.products.filter((product: any) =>
product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1);
}
Finally we should assign the main list of products to the filteredProducts and _listFilter to what we want.
constructor() {
this.filteredProducts = this.products;
this._listFilter= 'foo-bar';
}
last step is to change our template to bind to our filteredProducts property.

Resources