eBay / nice-modal-react

A modal state manager for React.
https://ebay.github.io/nice-modal-react
MIT License
1.96k stars 110 forks source link

Need to know modal status #63

Closed youf-olivier closed 2 years ago

youf-olivier commented 2 years ago

Before all thank you for this awesome lib ! ❤️

In our project we use this lib for manage all modals and it's just perfect.

However, we have some error handlers to manage error when we call apis.

In these handlers, we can open a modal (with Nicemodal.show we can) but we want to know which modals are open. For that, I would like to pass the state to the handler.

Would it be possible to export the state or the context ?

Thank you !

supnate commented 2 years ago

Thanks @youf-olivier !

Can you give an example about it? I'm not quite understand the requirement.

youf-olivier commented 2 years ago

Sure !

For example a little piece of component :

const Component = () => {
  const queryClient = useQueryClient();
  const { mutate, isLoading } =
    useApiPostRandom({
      mutation: {
        onSuccess: () => {
         console.log(Success)
        },
        onError: error => {
          handleApiClientError({
            error,
            store: { queryClient },
          });
        },
      },
    });

My Handler (I simplified it, but in my project the handler ditribute to a specific piece of code by the error code returned by the API):

export const handleApiClientError = (payload: HandlerPayload) => {
  if(NiceModal.state['modal-1'].visible){ // Here 
    NiceModal.show('error-modal');
  }else{
    NiceModal.show('modal-1');
  }
};

Long story short, my error handler can show a modal, but if the modal is already opened we have to show an error message in a second modal. But the code is located outside a component.

I imagined, in my component I could retrieve the state of all modals and put it in the handleApiClientError params for example :

const Component = () => {
  const queryClient = useQueryClient();
  const modalsContext = useContext(NiceModalContext);
  const openedModals = getModalOpened(modalsContext)
  const { mutate, isLoading } =
    useApiPostRandom({
      mutation: {
        onSuccess: () => {
         console.log(Success)
        },
        onError: error => {
          handleApiClientError({
            error,
            store: { queryClient },
            openedModals
          });
        },
      },
    });
supnate commented 2 years ago

Just exposed NiceModalContext, you can try to see if it works for you.

import { NiceModalContext } from 'nice-modal-react';
supnate commented 2 years ago

Published a new release v1.2.6.

youf-olivier commented 2 years ago

Thank you Barry Allen !!

youf-olivier commented 2 years ago

With this solution I resolved my problem <3