Skip to content
Advertisement

facing issue to store value in state and 3rd time state is not updating in react js

I am trying to get value from the radio button the problem is I can get the values but when I tried to store on my state it only updates 2 times after the 3rd time when I try to update the state it is not updating.

Radio buttons code.

JavaScript

I am trying to achieve output something like this

JavaScript

My ui:

enter image description here

My function: problem is here if (isExist) { isExist.options = { ...isExist.options, [name]: value, }; return prevValue; for this code the state is not updaing unlimited time.

JavaScript

Advertisement

Answer

There are few problems in your code.

1. Don’t change state variable directly.

In the following code, you are trying to change state variable directly. This may result unexpected result.

JavaScript

You can read more about it.

Why can’t I directly modify a component’s state

2. In this code, you should compare array item by title instead of name. Because you are using title.

JavaScript

3. Updated code based on your code in codesandbox

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement