Search code examples
reactjsparent-childreact-props

Passing State to parent immediately after updating React


Since react useState works like a queue ,I have issue accessing the data passed to the parent component by child component.

Input.js

    const Input = (props) => {
         const [isValid, setIsValid] = useState(false);
         const [value, setValue] = useState("");
    
          <input id={props.id} className="self-start justify-self-start border-gray-400 border-solid border rounded shadow"
              name={props.name}
              type={props.type}
              onChange={(e) => {
                let valid = isNaN(value);
                setIsValid(valid);
                props.handleChange(e, valid);
              }}/>
}

parent.js contains a function which access the data from the child component

 const handleChange = (e, valid) => {
          setFormData({
            ...formData, 
            [addr.name]: { value: e.target.value, isValid: valid },
          });
        };

The parent component always gets the previous validity of the input component. Is there any other way of passing data to parent component with latest state immediately after a state change in child component.


Solution

  • Update the valid argument in the handleChange callback based on the current value of the input field.

    onChange={(e) => {
          let valid = isNaN(e.target.value);
          setIsValid(valid);
          props.handleChange(e, valid);
        }}