Home > OS >  React Hooks: State is one step behind
React Hooks: State is one step behind

Time:09-27

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>

CodePudding user response:

This problem is due to the asynchronous behavior of setState. This method generates a "pending state transition" (see enter image description here

  • You can explicitly pass the new state value as part of the event being raised.
    • Related