简体   繁体   中英

How to I open a Bootstrap modal with data fetched from an API in React?

Hello I'm kinda new to this react thing and I'm starting off my learning process with a admin crud panel for some of my tables. For this question, let's take my table Services for instance, in the Service page there's a list of Services (so I got the read all to work :D) and now I want to be able to click on a user item in the list and it will read all the info of the user from an api and show his info in a modal window. How can I render the modal and fetch at the same time?

    <ul className="list-group">
        {this.state.services.map(service =>
        <li onClick={this.readOneService(service.id)} className="list-group-item" key={service.id}>{service.nom}
            <div className="btn-group btn-group-sm float-right" role="group">
                <button type="button" className="btn btn-primary" onClick={() => this.updateService(service.id)}>Update</button>
                <button type="button" className="btn btn-danger" onClick={() => this.deleteService(service.id)}>Delete</button>
            </div>
        </li>
        )}
    </ul>

Here's what I have in my read method:

    readOneService(serviceID) {
    // Read all services
    fetch(`/services/${serviceID}`)
        .then(res => res.json())
        .catch(err => { console.log(err) });
}

Do I have to put a render in there to show my modal?

Where are you getting your services from? I guess you fetch them a first time right? Aren't all the information you need in this.state.services already?

Because I'd highly recommand that you do fetch the data before, so that you don't do the job 2 times.

I will assume you are using react-bootstrap for the exemple:

const CustomModal = (service) => (
    <Modal.Dialog>
        <Modal.Header closeButton>
            <Modal.Title>{service.name}</Modal.Title>
        </Modal.Header>

        <Modal.Body>
            <p>{service.info1}</p>
            <p>{service.info2}</p>
            <p>{service.info3}</p>
        </Modal.Body>

        <Modal.Footer>
            <Button variant="secondary">Close</Button>
            <Button variant="primary"  onClick={() => this.updateService(service.id)}>Update</Button>
        </Modal.Footer>
    </Modal.Dialog>
);

You can also build a function customModal in your component, taking no parameter, and using its state instead.

Then you call it on click trigger as you did it already:

// Pass the service metadata
readOneService(service) {
    // Do here whatever you want
    CustomModal(service);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM