skip to Main Content

This code is where I modified the data, wherein I update the "checked" to whether "true" or "false". and this code works because when I console.log() it it updates the state.

    setRolesData((prevState) => {
        const newState = Array.from(prevState);
        newState[targetCb]["checked"] = e.target.checked;
        return newState;
    });
    console.log(rolesData);

Image of the result:
enter image description here

This code is where I loop thru the data that is updated, but the problem is it doesnt return the same data as the log data if tried for the second time.

    // get all checked roles
    const roleArr: any = [];
    rolesData.map((item, index) => {

        console.log(item.checked + " ^ " + item.name);

    });

Image of the Result:
enter image description here

3

Answers


  1. Chosen as BEST ANSWER

    So the problem is that the state is not updating immediately. I transferred the loop to a method wherein it handles the submission of the form.


  2. UseState is asynchronous. So, it will not work in a loop as expected. The better approach would be to use some gloabl variable and later update your state based on it.

    Login or Signup to reply.
  3. In React, components have a lifecycle that is based around the idea of preserving state. When you update a value in a component we effectively trigger a re-render of the component. So if you have a variable at the top of your component with a certain value and try to update this value inside a function, you’ll find that this value gets reset. React is replacing the component including the JavaScript variables inside it.

    In order to preserve any variables we use useState to persist the state of the component between re-renders. However, in a function, using useState does not save the value to state immediately. useState is an instruction that is sent to React that tells it that when the component re-renders, we need to save that value. If you try to access the value in state before your re-render has begun you will be using the "previous" value instead. In your case, your component will not re-render until the calling function has been completed.

    So how do you listen for changes?

    UseEffect is a special hook that takes an array of dependencies as "listeners". When we use useEffect and give it a value in state as a dependency, it’s telling it to run the code inside the useEffect if there is a mutation to that value.

    useEffect(() => {
    
        rolesData.map((item, index) => {
          console.log(item.checked + " ^ " + item.name);
        });
    
    }, [rolesData]);
    

    This code will run every time myState is changed, including on component initialisation. So we can use useEffect to process logic that requires the newly updated stateful values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search