I’m totally new to react js. I’m trying to update the array value based on the user input. I’m using the following code
This above works fine. But the issue is last index array not updated. For example: my tempquestion array has 10 value means 10 index array value is not update in the above code. Please any one have any idea ?
Asked
Active
Viewed 79 times
-1

Sridhar Karuppusamy
- 422
- 3
- 14
-
Hey there, can you please share your code snippet instead of a screenshot? It's much easier to read through and find the bug. – Ajin Kabeer May 25 '20 at 06:21
-
@AjinKabeer will share – Sridhar Karuppusamy May 25 '20 at 06:24
-
Your code seems to be correct. However you must note that the index value will only be till 9 for an array of size 10 – Shubham Khatri May 25 '20 at 06:30
-
@ShubhamKhatri Yes sir. My index value available till 9 so that I made a if condition like if(tempquestion.length > counter+1), the thing is 10 index its goes to else block but value is not set but if I print the answer value using console log means it’s print the answer value but it’s not updated in the array. It’s seems the issue in update array logic – Sridhar Karuppusamy May 25 '20 at 06:37
-
Ohh you mean to say that updated value is not being passed on to props.submitHandler – Shubham Khatri May 25 '20 at 06:38
-
@ShubhamKhatri yes... also I print the value before calling props.submitHandler and inside submitHandler both places I’m not getting the 10 index array value. It’s not updated but another 9 values are updated properly – Sridhar Karuppusamy May 25 '20 at 06:40
1 Answers
0
When on the last index, you pass on the value tempQuestions to props.submitHandler
after updating it. However you must know that the state updates are asynchronous and are affected by closures.
What it means is that the updated state will not reflect immediately after calling setTempQuestions but will be reflected post the re-render. However your current function execution will no see the changed value
Please check this post for an elaborated description: useState set method not reflecting change immediately
The solution here is to call the props.submitHandler
with the updated value and set the value to state within withe setTempQuestion
callback
setTempQuestion(tempQuestions => {
const updatedState= [
...tempQuestions.slice(0, counter),
{...tempQuestions[counter], answer},
...tempQuestions.slice(counter + 1),
]
props.submitHandler(updatedState);
return updatedState;
});

Shubham Khatri
- 270,417
- 55
- 406
- 400