1

I am trying to build a .net core web app with react. However I'm struggling with some API calls and function. This may be asked before but I could not find the solution for myself.

class Documents extends Component{

constructor(props){
    super(props);
    this.state = {
        docs: []
    };
    this.deleteHandle = this.deleteHandle.bind(this);
}
componentDidMount(){
    const url = 'api/Documents';
    fetch(url)
    .then((response) => {
        return response.json();
    })
    .then((data) =>{
        this.setState({
            docs: data
        });
    })
    .catch((error) => console.log(error));
}
renderDocuments(){
    return this.state.docs.map((doc) => (
        <Doc key={doc.id} doc = {doc}/>
    ));
}
deleteHandle(id) {
    fetch('api/Documents/'+id, { method: 'DELETE' })
        .then((response) => {
            return response.json();
        })
        .catch((error) => console(error));
}
render(){
    return (
        <ul>
            {this.renderDocuments()}
        </ul>
    );
}export default Documents;

And here is my Doc.js

const Doc = ({ doc }) => (
<li>
    <p>{doc.id} - {doc.documentCode} - {doc.documentName} - {doc.issuedDate}</p>
    <a onClick={this.deleteHandle(doc.id)}>Delete</a>
</li>);export default Doc;

The API and Get works fine, but when I clicked on DELETE button, it says:

_this.deleteHandle is not a function.

Please help.

3 Answers 3

3

Doc has no property that is called deleteHandle. Only Documents has. You need to pass a handler to Doc:

const Doc = ({ doc, onDelete }) => (
<li>
    <p>{doc.id} - {doc.documentCode} - {doc.documentName} - {doc.issuedDate}</p>
    <a onClick={onDelete}>Delete</a>
</li>);
export default Doc;

And in Documents.renderDocuments:

return this.state.docs.map((doc) => (
    <Doc key={doc.id} doc = {doc} onDelete={() => this.deleteHandle(doc.id)}/>
));
Sign up to request clarification or add additional context in comments.

Comments

1

You would need to pass down the delete event to each Doc so it can be used:

renderDocuments(){
    return this.state.docs.map((doc) => (
        <Doc key={doc.id} doc = {doc} onDelete={(id) => this.deleteHandle(id)} />
    ));
}

Then in Doc:

const Doc = ({ doc, onDelete }) => (
    <li>
        <p>{doc.id} - {doc.documentCode} - {doc.documentName} - {doc.issuedDate}</p>
        <a onClick={onDelete(doc.id)}>Delete</a>
    </li>);
export default Doc;

Comments

0

Your issue is that you call deleteHandle directly, instead of passing a function that calls it. With arrow functions, the solution is pretty straight forward:

<a onClick={()=> this.deleteHandle(doc.id)}>Delete</a>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.