Calling Api post method on button click in React

Viewed 9207

I have an event like below:

    handleDownload(e) {
    e.preventDefault();
    alert('Hi');
    let communityName = this.state['selectedCommunity'];
    let files = this.state[files];

    fetch(clientConfiguration['filesApi.local'], {
        method: 'POST',
        headers: new Headers(),
        body: JSON.stringify({ communityName: communityName, body: files })
    }).then((res) => res.json())
        .then((data) => console.log(data))
        .catch((err) => console.log(err))
};

I have a button as below:

    renderDownloadButton() {
    if (this.state.files && this.state.files.filter(i => i.checked).length) {
        return (
            <button id="download" styles="display: none;" onClick={this.handleDownload} >
                Download
    </button>
        );
    }
};

It fires but it is giving following error, any help please - thank you. At

let communityName = this.state['selectedCommunity'];

its giving me the error;

Can not read property state undefined

Any help please?

2 Answers

My guess is that you need to bind your handler, but it's really hard to tell without whole component code.

handleDownload = (e) => {
    e.preventDefault();
    alert('Hi');
    let communityName = this.state['selectedCommunity'];
    let files = this.state[files];

    fetch(clientConfiguration['filesApi.local'], {
        method: 'POST',
        headers: new Headers(),
        body: JSON.stringify({ communityName: communityName, body: files })
    }).then((res) => res.json())
        .then((data) => console.log(data))
        .catch((err) => console.log(err))
}

For the api post not fetching the error can be one possible case of CORS error that browser do not allow you to access other network(private and secured IP address) so you need to actually allow the proxy setting as I can see your post data don't have any proxy enabled. Here is the code I am attaching

This is the pseudo code please make changes accordingly in your fetch method:

    var targetUrl ='/downloadableReport'
        const res= fetch(targetUrl,{
            method: 'POST',
            headers: {
                        'Content-Type': "application/json; charset=utf-8",
            },
            body: JSON.stringify({
                              
                "requestData":{
                   "userName":"XXX",
                   "password":"XXXX",
                   "clientId":"XXXX",
                   "txnType":"XXXX"
                }
            })
        })
        .then(response => response.json())
        .catch(error =>{
                console.log(error)
            })
    

Also, you need to add setupProxy.js file (mind the name of the file should be this only) and add this code (with preferred changes)

    const proxy = require("http-proxy-middleware");
    module.exports = function(app) {
        app.use(
            proxy("/downloadableReport",{
                target:"http://192.168.1.220:8080/report/abc" ,
                changeOrigin:true
            })
        )
    };
Related