useState not updating data when passing from parent function component using ref

Viewed 732

I am trying to send data to child function component where I am binding form fields with that data. It works fine on first call, but when I am calling 2nd time the data never update in state, its always shows the first one.

This is parent which use the ref of child component

export default function Form1() {
    const [count, setCount] = useState(0);
    const [counter, setCounter] = useState(10);

    const AddNewRef = useRef();

    const clickMe=() => {

        setCount(count+1);
        setCounter(counter*2);

        AddNewRef.current.showDrawer(counter*2);

    }


    return (
        <div>
            <p>You clicked count: {count} & counter: {counter} times</p>
            {
                count > 10 ?
                (
                        <p className='red'>your count is greater then 10</p>
                ) :
                (
                    <p className='green'>your count is less then 10</p>
                )
            }
            <button onClick={() => clickMe()}>
                Click me
            </button>

           
            <AddNew ref={AddNewRef} Count={count} Counter={counter}  />

        </div>
    )
}
 

This is child component

const AddNew=forwardRef((props, ref) => {
    const[objCounter, setobjCounter] = useState(null);

    useImperativeHandle(
        ref,
        () => ({
            showDrawer(count) {


              setobjCounter(count);
              //only shows at first click at parent, Not updating on 2nd, 3rd click from parent and so on....


          }
        }),
    )

return (
    <>
      <Drawer
        title={<span> <i className='fa-solid fa-kaaba' /> Haj Setup Form</span>}
        width={window.innerWidth > 900 ? 800 : window.innerWidth - 50}
        onClose={onClose}
        visible={visible}
        bodyStyle={{ paddingBottom: 80 }}
        extra={
          <Space>
            <Button onClick={onClose}>Cancel</Button>
            <Button onClick={onClose} type="primary">
              Submit
            </Button>
          </Space>
        }
      >
        <Form 
      style={{display: formVisible ? 'block' : 'none'}}
          form={form}
          layout="vertical" 
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
                          
          hideRequiredMark>
            

            <Row gutter={16}>
              <Col xs={24} sm={24} md={24} lg={24}>

                <Form.Item
                  name="packageName"
                  label="Package Name"
                  rules={[{ required: true, message: 'Please enter package name' }]}
                  initialValue={objCounter}
                  
                  >
                  <Input style={{width: '100%'}}
                         maxLength={100}  /> 
                </Form.Item>
              </Col>
            </Row>
        </Form>
      </Drawer>
    </>
  )
});


export default AddNew
1 Answers

Since the state updates are working and you are simply wanting to update the form field, you can use the returned form reference from the useForm hook to update the form state. In this case, update the packageName field.

const AddNew = forwardRef((props, ref) => {
  const [objCounter, setobjCounter] = useState(13);
  const [visible, setVisible] = useState(false);
  const [formVisible, setformVisible] = useState(true);
  const [form] = Form.useForm();

  useImperativeHandle(ref, () => ({
    showDrawer(count) {
      setobjCounter(count);
      setVisible(true);

      form.setFieldsValue({
        packageName: count // <-- update the specific field
      });
    }
  }));

  const onClose = () => {
    setVisible(false);
  };

  return (
    ...
  );
});

Edit usestate-not-updating-data-when-passing-from-parent-functional-component-using-r (forked)

Related