Search code examples
reactjsreact-hooksreact-functional-component

Tried to use state variable inside another state variable, but it didn't work as expected it to, Why ? (in ReactJS using function component)


I was trying to use a state variables value inside another state variable, but when the other sub state variable was updated outside, its updated value didn't get reflected in parent state variable, why did this happened? can I not use state variable inside another state variable or is there any specific way to use it? Can anyone explain this please?

const [noOfPersonstForRoom, setNoOfPersonsForRoom] = useState([2]);

const [ageOfPerson1ForRoom, setAgeOfPerson1ForRoom] = useState([0]);
const [ageOfPerson2ForRoom, setAgeOfPerson2ForRoom] = useState([0]);

    const [rooms, setRooms] = useState([
    {
        roomNo: 1,
        noOfPersons: noOfPersonsForRoom[0], 
                    ageOfPerson1: ageOfPerson1ForRoom[0],
                    ageOfPerson2: ageOfPerson2ForRoom[0]
        

        
    },
]);

This is code of what I tried, with some changes.

To change sub state variable, I used following function, and it was called on onChange() of an input field:

const changeNoOfPersonsForRoom = (e, index) => {
        let newNoOfPersonsForRoom = e.target.value;
        setNoOfPersonsForRoom([
            ...noOfPersonsForRoom.slice(0, index),
            e.target.value,
            ...noOfPersonsForRoom.slice(index + 1),
        ]);

Solution

  • Could you add how you update your state(s)?

    But in general, states are not bound or connected to each other. If you change one state, it won't update any other state.

    const [rooms, setRooms] = useState([
        {
            roomNo: 1,
            noOfPersons: noOfPersonsForRoom[0], 
            ageOfPerson1: ageOfPerson1ForRoom[0],
            ageOfPerson2: ageOfPerson2ForRoom[0]
        },
    

    Given your example, you just set the initial state of rooms with the values of your previous states. Nothing more. If you need to update several states, you have to update each of them separately.