I have an API where I want to put a template for each book in order to edit it on the same page.
Unfortunately, it always shows me the last data in the list and not the data I want. What I actually want is when I press the PUT button for "id 2", I want my model to show me the data for "id 2" and not the last id from the database (for example, "id 10").
Here is my constructor and my call from my api :
constructor(props) {
super(props)
this.state = {
data: [],
openPost: false,
openPut: false
}
}
componentDidMount() {
axios.get('https://127.0.0.1:8000/api/books')
.then(response => {
this.setState({
data: response.data
})
})
}
Here is my code:
{
data.map(book =>
<div key={book.id}>
<div className="card ml-auto mr-auto mb-3">
<div className="card-body" key={book.id}>
<h2 className="card-title">{book.title}</h2>
<h6 className="card-subtitle mb-2 text-muted">{book.subtitle}</h6>
<p className="card-text">{book.content}</p>
<Model id={"Model_put-" book.id} value={book.id} trigger={this.state.openPut} setTrigger={!this.state.openPut} id_book={book.id}>
<button onClick={() => this.setState({ openPut: false })} className="close-btn btn-danger">X</button>
<h3>My Model</h3>
<p>This is my button triggered Model</p>
<input type="text" name="id" className='form-control' value={book.id} ></input>
<div className="row">
<div className="col">
<input type="text" name="title" className='form-control' placeholder='Title' ></input>
</div>
<div className="col">
<input type="text" name="content" className='form-control' placeholder="Content" ></input>
</div>
</div>
<div className="col">
<textarea className='form-control mt-2' defaultValue={book.content} />
</div>
</Model>
<button onClick={() => this.setState({ openPut: true })} type="button" className="btn btn-warning" id={"book-" book.id} href="#">
PUT
</button>
</div>
</div>
</div>)
}
And the contents of my Modal.js file:
return (this.props.trigger) ? (
<div className="modal">
<div className="modal-inner">
{ this.props.children }
</div>
</div>
) : ""
Thanks in advance !
CodePudding user response:
Every one one your modals is looking at the same openPut variable, which is a boolean, so they are either all open, or all closed. It just so happens that the last one is the only visible one. Quickest fix is:
<Model
id={"Model_put-" book.id}
value={book.id}
trigger={this.state.openPut === book.id}
setTrigger={!this.state.openPut} id_book={book.id}
>
/* ... */
</Model>
<button
onClick={() => this.setState({ openPut: book.id })}
type="button"
className="btn btn-warning"
id={"book-" book.id}
href="#"
>
PUT
</button>