3

I have a file called agent.ts that contains axios interceptors. In those interceptors I watch for any status code that is >= 400 and <= 500. When such error occurs, I am invoking react-toastify toast.

Everything works perfect so far. What I want to be able to do though, is to use html as body of the message. Usually I would do that by creating a custom component and then using the component as body of the toast message. But because I am using react-toastify outsode of component in a regular typescript file, I am getting an compilation error.

Here is part of my code:

axios.interceptors.response.use(undefined, async (error) => {
  if (error.message === 'Network Error' && !error.response) {
    toast.error('Network error - make sure API is running!');
  }

  const { status, data } = error.response;

  if (status >= 400 && status < 500) {
    if (!data || !data.errors) {
      toast.error(`${status} API error. Please check the terminal!`);
      return;
    }

    console.warn('API Errors:', data.errors);
    Object.keys(data.errors).forEach(function (key) {
      toast.warn(data.errors[key].toString());
    });
  }

  if (status === 500) {
    toast.error('Server error - check the terminal for more info!');
  }

  throw error.response;
});

I am attaching a screenshot of the compile error that I see: enter image description here

Can you please advice me what is the best approach here ?

Dobromir Ivanov
  • 313
  • 4
  • 12

2 Answers2

0

If you read the API docs, there's a section that allows custom styling under options.style, as well as adding custom class names. To do what you tried though, you can also use toast.custom:

toast.custom(<div>...</div>);
code
  • 5,690
  • 4
  • 17
  • 39
  • Hey mate, I think you are talking about different library. react-hot-toast, while I was refering to react-toastify (https://www.npmjs.com/package/react-toastify). Anyway, your comment is still usefull, because I can use this as an alternative and completely change the library that I am using in case I cannot manage to fix the issue mentioned in the post. – Dobromir Ivanov Jan 09 '23 at 20:13
  • @DobromirIvanov oh, I'm sorry. I didn't see that you specified in your question and assumed it was React Hot Toast. – code Jan 09 '23 at 20:21
0

I managed to find solution. Basically I was able to use react components by changing the file type of the agent.ts from .ts to .tsx. Thats it, you I don't need anything else.

As an alternative if this approach is not working for some reason, I can also use React.createElement() directly:

let node = React.createElement('div', null, `Hello`, React.createElement('br', null),React.createElement('br', null), "world!");
Dobromir Ivanov
  • 313
  • 4
  • 12