iamhosseindhv / notistack

Highly customizable notification snackbars (toasts) that can be stacked on top of each other
https://notistack.com
Other
3.93k stars 298 forks source link

[Question/Feature] How to create a snackbar inside a service ? #85

Closed VincentLanglet closed 5 years ago

VincentLanglet commented 5 years ago

I use Apollo with an error link written this way:

import { ErrorResponse } from 'apollo-link-error';
import { GraphQLError } from 'graphql';

export const errorHandler = ({ graphQLErrors, networkError }: ErrorResponse): void => {
  if (graphQLErrors) {
    graphQLErrors.map((error: GraphQLError) => {
      console.error(error);
    });
  }

  if (networkError) {
    console.error(`Network error: ${networkError.message}`);
  }
};

export default onError(errorHandler);

Is it possible to replace console.error by something like enqueueSnackbar ?

iamhosseindhv commented 5 years ago

@VincentLanglet notistack is not designed to work outside the component code. In my projects I tend to use something like the following:

fetchApi(url, method, payload)
    .then(() => {
           // ... enqueue snackbar
           // ... redirect to /dashboard page
    })
    .catch((err) => this.props.enqueueSnackbar(err, { variant: 'error' } ))

Or dispatch a enqueue action from Saga (if I'm using redux).

But there're other solutions presented here: #30 Namely this one: https://github.com/iamhosseindhv/notistack/issues/30#issuecomment-455822993

Hope this was useful.

MichaelBoselowitz commented 5 years ago

Hey @iamhosseindhv, I also have this use case (specifically from an API polling service and a PouchDB changes service). I've looked at #30's workaround, and it should work for me, but it would be great if there was a direct method.

If it's something that could go on the roadmap that would be amazing. Either way, thank you for your work on this library.

iamhosseindhv commented 5 years ago

I agree it'd be nice to have support for it.

Any implementation suggestion is welcome.