I have a component ResultComponent and I wanted whenever I click "Edit" button, I will get the result of the value of attribute data-id and store it in state (property idClicked). I have initial value of the state.idClicked (I set it as null).
Now is the problem, when I first click it will alway return null value, the second try return expected value. Now I want it will return the right value on the first click.
Here is my code and my result:
My result in console:
My code:
import React from "react"; import "./ResultComponent.scss"; interface IPropsType { jobList: { id: number | null; jobName: string | null; }[]; handleDeleteJobList: (id: number) => void; } interface IStateType { isEdited: boolean; idClicked: number | null; } class ResultComponent extends React.Component<IPropsType, IStateType> { constructor(props: IPropsType) { super(props); this.state = { isEdited: false, idClicked: null, }; } handleOnClickDelete = (event: any): void => { const currentID = parseInt(event.target.getAttribute("data-id")); this.props.handleDeleteJobList(currentID); }; handleOnClickEdit = (event: any) => { event.preventDefault(); const idButtonClicked = event.currentTarget.getAttribute("data-id"); this.setState({ isEdited: !this.state.isEdited, idClicked: parseInt(idButtonClicked), }); console.log(this.state.idClicked); }; handleOnClickSave = (event: any) => { this.setState({ isEdited: !this.state.isEdited, }); };render(): React.ReactNode { const { jobList }: IPropsType = this.props;
return ( <> <table> <thead> <tr> <th>ID</th> <th>Things To do</th> <th colSpan={2}>Actions</th> </tr> </thead> <tbody> {jobList.map((job, index) => ( <tr key={index}> <td>{job.id}</td> {!this.state.isEdited ? ( <td>{job.jobName}</td> ) : ( <td> <input defaultValue={job.jobName} // placeholder={idClicked} ></input> </td> )}
<td> {!this.state.isEdited ? ( <button data-id={job.id} onClick={(e) => this.handleOnClickEdit(e)} > Edit </button> ) : ( <button data-id={job.id} onClick={(e) => this.handleOnClickSave(e)} > Save </button> )} </td> <td> <button data-id={job.id} onClick={(event) => this.handleOnClickDelete(event)} > Delete </button> </td> </tr> ))} </tbody> </table> </> ); } }
export default ResultComponent;
