Home > Blockchain >  how correctly 'reset' useState when close modal reactJS
how correctly 'reset' useState when close modal reactJS

Time:04-08

I would like to explain my problem of the day.

Currently 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

iam open to any proposal thank you very much.

ps: leadsOptions in select is data ofc , ps 2 : 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>
);
}

CodePudding user response:

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();}} />
 
  • Related