javascriptreactjsreact-hooks

How correctly 'reset' useState when close modal


I use a modal in this modal I select a value, this works correctly.

My problem and the following, when I click on the cancel button or the cross to close. And if I open the modal again, the value select before and still present

I would like to return to its initial state when I click on cancel or the cross and of course when I open the modal no value in select.

leadsOptions in select is data of course, maybe a useeffect/ prevStateReset to Initial State?

import React, { useState, useEffect } from "react"

function LeadModal({ isOpen, onClose }) {
 const [leadId, setLeadId] = useState(null);
 return (
    <Modal
        open={isOpen}
        getOpen={onClose}
    >
        <PanelHeader>
            <PanelTitle>
                add lead
            </PanelTitle>
            <SvgIcon
                onClick={onClose}
            />
        </PanelHeader>
          <PanelBody className="space-y-1 mb-2 ">
                            <Label>
                                Sélect lead
                            </Label>
                            <div>
                                <Select
                                    options={leadsOptions}
                                    placeholder="leads"
                                    getValue={(values) => {
                                        setleadId(values.value);
                                    }}
                                    value={leadId}
                                />
                            </div>
                        </PanelBody>
                        <PanelFooter>
                            <div>
                                <Button onClick={onClose}>
                                    Annuler
                                </Button>
                            </div>
                        </PanelFooter>
                    </>
    </Modal>
);
}

Solution

  • You are not clearing your state data when you open the modal again. Just update the state value with the initial value before closing or canceling the modal or something like this.

    <SvgIcon onClick={() => {setLeadId(null); onClose();}} />