Home > Back-end >  React state: unable to get updated value inside onChange
React state: unable to get updated value inside onChange

Time:04-11

I am using an array of components that are interested depending on various conditions i.e the order and number of elements in the array are dynamic as shown below:

  useEffect(() => {
    const comp = [];

    // if(condition1===true){
    comp.push(<MyComp onChange={onValueChange} />);
    // }
    // if(condition2===true){
    comp.push(<YourComp onChange={onValueChange} />);
    // }
    // if(condition3===true){
    comp.push(<HisComp onChange={onValueChange} />);
    // }
    setComponents(comp);
  }, []);

To each of the components in the array, there could be some sort of input control like input-text, input-number, text-area, chips, radio, checkbox, etc.
So there is an onChange event linked to each of these components.

I am using a common onValueChange function which is passed as a callback to these components. In the onValueChange I need 2 things:

  • changed value (from child component)
  • activeIndex (from same component)
  const onValueChange = (val) => {
    console.log("onChange Valled", val, "activeIndex==", activeIndex);
  };

But here I am not able to fetch the updated value on activeIndex, it always gives zero no matter in what active step I am in.

Sandbox DEMO

CodePudding user response:

Try using useCallback with dependency array. Also try to avoid storing components in state.

const onValueChange = useCallback((val) => {
    console.log("onChange Valled", val, "activeIndex==", activeIndex);
  },[activeIndex];

For rendering try something like below.

condition1===true && <MyComp onChange={onValueChange} />

or create a function which returns the component eg: getComponent(condition) and use this in render/return. Make sure you wrap getComponent in useCallback with empty dependency array []

CodePudding user response:

You need to add a dependency in useEffect hook.

useEffect(() => {
    const comp = [];

    // if(condition1===true){
    comp.push(<MyComp onChange={onValueChange} />);
    // }
    // if(condition2===true){
    comp.push(<YourComp onChange={onValueChange} />);
    // }
    // if(condition3===true){
    comp.push(<HisComp onChange={onValueChange} />);
    // }
    setComponents(comp);
  }, [onValueChange]);

CodePudding user response:

 useEffect(() => {

    setComponents((previousValues)=>{
        // if you want to add on previous state
        const comp = [...previousValues];

        // if you want to overwrite previous state
        const comp = [];

        if(condition1===true){
          comp.push();
        }
        if(condition2===true){
         comp.push();
        }
        if(condition3===true){
          comp.push();
        }
      return comp;
    });
  }, []);
  • Related