Can't add anything correctly to useState array? - reactjs

I'm new in React. I writed that code by following a tutorial.
I tried many ways but couldn't add new arrays correctly into useState array.
function TodoApp(){
const [liste, setListe] = useState( [] );
function listeyeEkle(e) {
console.log(e); // {yazi: "First", id: 0} It's great here, no problems.
setListe( [e, ...liste] ) // Console log in Picture 1
setListe( e ); // Console log in Picture 2
console.log(liste);
}
Picture 1
Picture 2
Something going wrong and it's adding a empty object into array??
Do you have any idea?
Thanks!

The way you wrote it, you are setting the correct array first:
setListe( [e, ...liste] )
Afterwards you are setting the state to the value of the inputs element:
setListe( e )
I think you should remove this line? Then it will work! But might not show up in console.log(liste), due to the async nature of setState()!

Related

I'm trying to update the row values in MUI datagrid, i'm using processRowUpdate property.But, I'm only getting recent updated cell value only

Here **Skills ** will have the array of objects which includes the values Which I'm updating.
const handleProcessRowUpdate = (newRow, oldRow) => {
console.log("update called", newRow, oldRow);
let skills = assignedskillList;
let result = skills.map((item) => {
if (item.skill_id == params.skill_id) {
console.log("ids", params.skill_id, item.skill_id);
if (item.skill_level !== newRow.skill_level) {
item.skill_level = newRow.skill_level;
}
if ((item.target_level = newRow.target_level)) {
item.target_level = newRow.target_level;
}
console.log("idsss", item.skill_level, item.target_level); // here for first column edit //I'm getting current edited value only, for the second col edit getting only second column //value.the first value is resetting
}
setUpdatedVal(result); //I'm setting this in a new array to use this for post to API
return item;
});
tried onCellEdit commit , but, thats not worked. any other solutions ?
or correct me if I'm setting the value wrongly.
Thanks In advance.....
Finally, I found it.
Hope it might be helpful for someone in future
instead of updating the value inside the map. I've just defined a result array outside and assigned the map to that, Now I can get all updated values..
Thank you...

How to update an array of arrays by replacing an array item with the new corresponding array item? Reactjs

Apologies for the poorly worded title, I'm not sure how to phrase the question. I have made a quiz app in React which allows the user to choose the number of questions and for each question, there are five possible answers they can toggle between.
Because of the toggle feature, if they toggle between the possible answers, I need to be able to add the new array and replace the old corresponding one, which will then be checked to see if they are correct when they check the score. I've tried for hours to figure this out but I just can't. I've come sort of close but it only works if the user doesn't toggle between the answers.
Here's my code so far and the only semi-workable solution that I've come up with but is ugly and only works if the user doesn't toggle between answers for the same question.
function getDataFromQuestionComponent(dataFromComponent){
getQuizData.push(dataFromComponent)
// stop the score data array from growing continously
if (getQuizData.length > amount) {
maintainScoreArrayLength(getQuizData)
}
}
function maintainScoreArrayLength(quizDataArray){
// to find if which answers are matching so the original can be replaced
// with the new answer (too obscure - find a better solution)
let lastItemZeroIndexText = (quizDataArray[quizDataArray.length - 1][0].body)
for (let i=0; i<quizDataArray.length; i++) {
if (lastItemZeroIndexText === getQuizData[i][0].body) {
newArray.push(getQuizData.indexOf(getQuizData[i]))
}
}
// remove the previous item from the array
getQuizData.splice(newArray[0], 1)
}
This is what the array of object arrays looks like in the console:
The .map array method and array destructuring make it possible to do this more cleanly.
I can't quite tell how you are storing the data for the quiz questions/answers, but here's an example of how you could do it if you are saving all of the quiz data in a state object and storing the index of the current question:
const [quizData, setQuizData] = useState(initialQuizData);
const [currentQuestion, setCurrentQuestion] = useState(0);
const onSelectAnswer = (selectedAnswer) => {
// create an object with updated data for the current question
const updatedQuestionData = {
...quizData[currentQuestion],
multipleChoiceAnswers: quizData[
currentQuestion
].multipleChoiceAnswers.map((answerOption) => ({
...answerOption,
selected: selectedAnswer === answerOption.body
}))
};
// iterate through the questions
// and save either the
// updatedQuestionData or the prevState data
// (store the updatedQuestionData over the prevState data for that question)
setQuizData((prevState) => [
...prevState.map((question, index) =>
currentQuestion === index ? updatedQuestionData : question
)
]);
};
To break it down, we create a copy of the answers array but we set selected to false unless it is the answer the user just clicked:
multipleChoiceAnswers.map(answerOption) => ({
...answerOption,
selected: selectedAnswer === answerOption.body
})
The updated question object is made by copying the data from the current question, then overriding the array of answers with the updated copy of the answers we just made in the code snippet above. That is what is happening in this part:
const updatedQuestionData = {
...quizData[currentQuestion],
multipleChoiceAnswers: // The updated answers array
};
Here's a full example on code sandbox:

Write data in to nested object in firebase firestore

I have a data structure that looks as follows:
This is the top level of the collection:
I want to write to increment the field count but I can't do it. I've tried so many different methods that I'd rather not go through all of them. The closest I've gotten was through:
const pageRef = admin.firestore().collection("pages").doc(image.page);
pageRef.set(
{
[`images.${image.position}.count`]: admin.firestore.FieldValue.increment(
1
),
},
{ merge: true }
);
But that leaves me with:
Please help. Changing the structure of pages is an option.
This is what I've tried to replicate:
Update fields in nested objects in firestore documents?
The issue is on how the point notaition is being used.
In the Post you shared the example they use is:
var setAda = dbFirestore.collection('users').doc('alovelace').update({
"first.test": "12345"
});
Applying this to your Code and model would be:
const pageRef = admin.firestore().collection("pages").doc(image.page);
pageRef.set(
{
`images[${image.position}].count`: admin.firestore.FieldValue.increment(
1
),
},
{ merge: true }
);
This will affect the element in the Array Images, the element image.position its value count.

Angular 2 / Typescript - how to check an array of objects to see if a property has the same value?

This question does it in Javascript, but I would have thought in Typescript I could do some kind of map/filter operation to do the same thing.
I have an array of objects called Room. Each Room has a property called Width (which is actually a string, eg '4m', '5m', '6.5m').
I need to check the entire array to see if all the widths are the same.
Based on that question I have this, but I was wondering if TypeScript has something better:
let areWidthsTheSame = true;
this.qp.rooms.forEach(function(room, index, rooms) {
if (rooms[index] != rooms[index+1]) areWidthsTheSame = false;
});
Any ideas?
FYI the linked question has a comment that links to these performance tests, which are interesting in the context of this question:
This can be done in the following way:
const widthArr = rooms.map(r => r.width);
const isSameWidth = widthArr.length === 0 ? true :
widthArr.every(val => val === widthArr[0]);
We first convert the rooms array to an array of widths and then we check if all values in widths arrays are equal.

Working with Mongoose Arrays synchronously via async-await [duplicate]

This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 6 years ago.
So I've been trying to figure out what exactly I'm missing in a logic loop I've created. The following example closely recreates my situation:
async function x() {
const items = await Items.find().exec();
console.log(items);
for(item in items) {
console.log(item);
}
}
So the outcome for that little code block for me is that items holds an array of mongoose documents as expected, but here is the issue: item apparently is 0.
When I look at the mongoose document the only value that is 0 on it is the __v value, which in my understanding is the version that document is at. Am I just missing something or is this just not possible?
To note this returns as expected:
async function x() {
const items = await Items.find().exec();
console.log(items);
items.forEach(item => {
console.log(item);
});
}
This logs both the array and a single mongoose document, the issue is I'm looking to do another async call in that second loop that I want to await so if that's not possible I'll have to break it up more I guess, but I'd like ot know where that 0 is coming from if possible.
EDIT: To clarify, I have tried running toObject on both but it doesn't seem to change anything, and actually on the array it says toObject isn't a function of the array.
EDIT 2: I was not asking why for...in was bad, I was asking why it was not iterating over the "array" I had, it was due to the fact that mongoose returns a collection and for...in iterates over the enumerable properties of an object.
iterating over an array using
for(item in ['a', 'b']) {
console.log(item)
}
will give you the array indexes: 0, 1
You are looking for
for(const item of ['a', 'b']) {
console.log(item)
}
And that will print values: a, b
Check this

Resources