Thanh T Dao
Thanh T Dao

Reputation: 11

API request in React

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.

Upvotes: 1

Views: 61

Answers (3)

egorchik
egorchik

Reputation: 549

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>

Upvotes: 0

Davin Tryon
Davin Tryon

Reputation: 67296

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;

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174329

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

Upvotes: 3

Related Questions