How can i pop a value with key from local state? - reactjs

I have a local state as object:
selectedDates = {};
When i click on icons I am getting ID´s in my local state as object key, value pair.
// We "open" the value to extract the relevant informations
const [key, value] = calendarIconId.split("=");
// Add the new value inside of the object
this.state.selectedDatesTemp[key] = value;
// Turn the object into an array, we gotta rebuild the values
const date = Object.keys(this.state.selectedDatesTemp).map(
x => `${x}=${this.state.selectedDatesTemp[x]}`
);
How can i delete an object from the local state?

You can use delete to achieve it:
const { selectedDatesTemp } = this.state;
delete selectedDatesTemp[key];

Related

Why am I mutating the original array with filter method? [React]

After executing the newData[0].id = newValue I am actually updating the react initialData state. How is that possible?
Is my understanding that filter should return a new array different than the original one, also I am not ussing the setState feature so I don't understand why the state is changing.
Because arrays are mutable. it will keep the reference to the original array even after filtering.
use the spread operator to avoid mutating the original array
const data = [...newData]
data[0].id = newValue
As per the new beta docs on updating items in array
setInitialData(prev => {
// create a new array
const withReplaced = prev.map(elem => {
if (elem.id === id) {
const newVal = //set new value
// create a new updated element
return {
...elem,
id: newVal
}
} else {
// The rest haven't changed
return elem;
}
});
return withReplaced;
})
Hope it helps
you can't update the initialData,but the you can update the son of the array.And if you don't use "setData".The views won't change.

Cannot delete property of an object in an array- React,redux-toolkit

I have an array, which is from redux-store, contains list of object. I use delete operator to delete some certain property of object in the array in a function, but return an errors "Cannot delete property 'message' of #"
Below as my codes:
const transactionSuccess = (data) => {
notifySuccess("payment success");
console.log("products", products);
for (const item of products) {
delete item.message;
delete item.sizes;
}
const userLocal = JSON.parse(localStorage.getItem("user"));
const { token } = userLocal;
const object = {
products: products,
isPaid: data.paid,
description: "paypal;",
};
postAPICart(object, token, history);
};
console.log('products', products) returns 3 objects in an array
Firstly, I really appreciate andres and phry for trying to help me with that question.
I finally reach out the key problem in my code, it's all about shadow and deep copy
const products = [{item1},{item2}] // an array contains list of object
const copiedProducts = [...products] or const copiedProducts = products.map(item => item) will return SHADOW COPPY of products. Spread operator and map dont actually create new item1 and item2 object. Therefore, if you try to delete or add new property in item1 or item2 of copiedProducts, item1 and 2 in original products also be override, then complier then return an error
I came up with this solution:
const productsCopy = JSON.parse(JSON.stringify(products)); // create a deep copy, all objects are totally separated from original one
Below is a link help me above solution:
https://www.javascripttutorial.net/object/3-ways-to-copy-objects-in-javascript/#:~:text=A%20deep%20copying%20means%20that,connected%20to%20the%20original%20variable.
Happy coding day guys
You cannot change values in your store outside of a reducer. And now you may say "hey, this is not a store value", but it most likely is just a reference to the store - and changing any of your products here would in turn also change the store.
You can do something like this:
const newProducts = products.map(({ message, sizes, ...rest }) => rest)
this will leave the original objects alone and create an array of new objects with everything except messages and size for you to work with

How to check if object matches with values on checkbox click?

I currently have a function addToProduction. This loops over data and returns a new object with IDs and databases. The changeHandler on the checkbox currently displays all the values however I want to be able to log the correct id and database from the correct row and not all values. This will then be stored and appended to the databaseChanges array when clicked.
You can grab the id from the onChange event object.
const addToProduction = e => {
const { id } = e.target;
... // do whatever with id
console.log(id)
}
And attach the test id to the checkbox id attribute
<Checkbox
mainColor
changeHandler={addToProduction}
data={{}}
id={test.id} // <-- attach id to checkbox
/>
EDIT
Pass entire test object to curried handler to append object into array. The curried function takes the test object and returns a function to be used as the callback (now ignores the event object, but you can accept that if you need anything from it).
const addToProduction = test => () => {
const { databases, id } = test;
console.log(databases, id)
// append `{ id, databases }` to databaseChanges array
}
...
<Checkbox
mainColor
changeHandler={addToProduction(test)}
data={{}}
/>

unable to set record in react usestate array from sqlite

I am using sqlite for local storage in react native but when I tried to fetch record and set it into the useState , it doesn't update the state
here is the code
const SelectQuery=async()=>{
const token = await AsyncStorage.getItem('docToken')
let selectQuery = await ExecuteQuery("SELECT * FROM DoctorConversations where d_phone=?",[token]);
var rows = selectQuery.rows;
var temp = [];
for (let i = 0; i < rows.length; i++) {
temp.push(rows.item(i))
}
return temp;
}
This is how I am calling
SelectQuery().then(res=>res.map(item=>{
setFlatListItem([...flatListItem,item])
}))
I guess that you have:
const [flatListItem, setFlatListItem] = useState([]);
setFlatListItem changes internal state and schedules a rerender. flatListItem gets a new value only on the next render.
You need to use functional updates to modify the current internal state:
setFlatListItem(state => [...state, item])
If you want to replace the whole list, you do not need to map individual items:
SelectQuery().then(res=> setFlatListItem(res))
Note that flatListItem is a bad name in your case since it holds an array. You should probably rename it to just [flatList, setFlatList].

How to push array of objects into state using hooks

I have a useState as const [responses, setResponses] = useState([]);
I get the response and log it as follows :
const tempResults = res.data.data;
console.log(tempResults.length);
console.log(tempResults);
The log shows as:
When I click to open the Array of 6 items, results are .
So it is an array of objects.
I tried to set the initial value of the state as per the object
{
"index": 0,
"ds": "2020-03-06",
"yhat_lower": -10712.5597359237,
"yhat_upper": 25376.4649581317,
"yhat": 6955.3671910982,
"mape": 21.4472070205,
"rmse": 667.0969808414,
"mae": 475.3343871057,
"smape": 5.143548286
}
But when I logged, the state only had the initial value and had not appended the response array.
I am setting state as :
setResponses(...responses, tempResults);
const x = typeof responses;
console.log("TypeOfResponse", x);
console.log("RESPONSES ", responses);
However, the state of the 'responses' object as per console is this:
So it is not able to save the Array object into state. What could be wrong? Any suggestions, please?
if res.data.data is an array
then set to setResponses like this
setResponses(res.data.data)
or
setResponses([...responses, ...res.data.data])

Resources