Jack23
Jack23

Reputation: 1396

ReactJS: return an alert after fetch

I make an api call

report.tsx

  if (buttonClick === 'pdf') {
        getReportPDF(params, sort);
   }

report-reducer.ts

export const getReportPDF = (search, sort) => {
  const params = new URLSearchParams(search) ? new URLSearchParams(search).toString() : null;
  const sorting = new URLSearchParams(sort) ? new URLSearchParams(sort).toString() : null;

  const requestUrl = `${apiUrlPDF}?${params}${Object.keys(sort).length > 0 ? '&' + sorting : ''}`;
 
  fetch(requestUrl).then(response => {
    response
      .blob()
      .then(blob => {
        if (blob.type === 'application/problem+json') {
          alert('Nothing');
        } else {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = 'report.pdf';
          a.click();
        }
      })
      .catch(error => console.log('error is ', error));
  });
};

Now my problem is: at the moment I'm using an alert directly in the reducer, but if I would show a different alert

( for example usign bootstrap:

<div class="alert alert-primary" role="alert">
  A simple primary alert with <a href="#" class="alert-link">an example link</a>. Give it a click if you like.
</div>

)

in the report.tsx, how can I do? I should return something in if (blob.type === 'application/problem+json') ??

thank you

Upvotes: 0

Views: 164

Answers (1)

Erfan
Erfan

Reputation: 1802

You can create a state in report.tsx that controls showing of alert:

const [isAlertShowing,setAlertShowing]=useState(false)

Now make getReportPDF take an extra callback parameter in case of success:

    export const getReportPDF = (search, sort, callback) => {
  const params = new URLSearchParams(search) ? new URLSearchParams(search).toString() : null;
  const sorting = new URLSearchParams(sort) ? new URLSearchParams(sort).toString() : null;

  const requestUrl = `${apiUrlPDF}?${params}${Object.keys(sort).length > 0 ? '&' + sorting : ''}`;
 
  fetch(requestUrl).then(response => {
    response
      .blob()
      .then(blob => {
        if (blob.type === 'application/problem+json') {
          callback() // invoke the callback here or anywhere else you that you want
        } else {
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = 'report.pdf';
          a.click();
        }
      })
      .catch(error => console.log('error is ', error));
  });
};

Then pass a function as callback, that sets isAlertShowing to true

    const activateAlert=()=>setAlertShowing(true)

    if (buttonClick === 'pdf') {
        getReportPDF(params, sort, activateAlert);
   }

Finally, in render of the component, show the alert whenever isAlertShowing is true:

For example:

return (
   {isAlertShowing && <div class="alert alert-primary" role="alert" .... 

Upvotes: 1

Related Questions