React Hooks: State is one step behind

Viewed 1731

I have a modal that opens on click event. It gets the event data (date and time string) and displays it inside the modal. The problem is that my state is always one step behind. The content being displayed by the modal is always in the previous state. When I close the modal and reopen it, It does render the content but It is the previous event. How to solve this issue? am I using the react hooks wrong? I cannot post the whole code as It's quite large so I am just posting the parts where I am using hooks, please let me know if you need more information I will provide it.

  const [isModalVisible, setIsModalVisible] = useState(false)
  const [modelContent, setModalContent] = useState('')
  const [modalTitle, setModalTitle] = useState('')
 

const handleEventAdd = (e) => {
    form.resetFields()
    setModalTitle('Add an Event')
    const event = _.cloneDeep(e)
      form.setFieldsValue({
        datePicker: dateString,
        timeRangePicker: [dateString, eventEnd.date],
      })
    }
    const content = () => (
      <div>
        <Form
          form={form}
          initialValues={{
            datePicker: moment(e.start),
            timeRangePicker: [moment(e.start), moment(e.end)],
          }}
        >
                  <Form.Item name="datePicker" label="Current Event Date">
                    <DatePicker
                      className="w-100"
                      format={preferredDateFormat}
                      onChange={setValueDate}
                    />
                  </Form.Item>
          <Form.Item>
            <Button
              onClick={() => {
                form
                  .validateFields()
                  .then((values) => {
                    form.resetFields()
                  })
              }}
            >
              Add Event
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
    setModalContent(content)
    setIsModalVisible(true)
  }

const handleModalClose = () => {
    setIsModalVisible(false)
    form.resetFields()
    setModalContent('')
  }

UPDATE:: my return function consists,

<Modal visible={isModalVisible} footer={null} onCancel={handleModalClose} title={modalTitle}>
    {modelContent}
  </Modal>
1 Answers

This problem is due to the asynchronous behavior of setState. This method generates a "pending state transition" (see this for more information). In order to solve this issue, you have two options:

  1. use ref instead of state. In contrast to state, ref has synchronous behavior. I have developed an example for myself that you can check out here. you can see that there is an asynchronous behavior in the state (dialog box vs. in webpage). enter image description here
  2. You can explicitly pass the new state value as part of the event being raised.
Related