У меня есть файл, который создает контекст Modal
, чтобы легко создать модал из всех компонентов через хук useModal
. Этот провайдер обернут вокруг всех компонентов, поэтому к нему можно получить доступ где угодно.
Modal.setAppElement("#root");
const ModalContext = React.createContext();
const useModal = () => {
const context = React.useContext(ModalContext);
if (!context) {
throw new Error(`useModal must be used within a ModalProvider`);
}
return context;
};
const ModalProvider = props => {
const defaultContent = (
<>
<Button modifier={"Button--grey"} onClick={() => setModalState(false)}>
Close
</Button>
<Button modifier={"Button--reloadPage"} onClick={() => reloadPage()}>
Refresh
</Button>
</>
);
const reloadPage = () => {
// Somehow want to access the getSocialGroupData function here
};
const [modalState, setModalState] = useState({
isOpen: false
});
const openModal = ({
contentLabel,
portalClassName,
overlayClassName,
className,
shouldCloseOnOverlayClick,
shouldCloseOnEsc,
content
}) => {
setModalState({
isOpen: true,
contentLabel: contentLabel ? contentLabel : "Unexpected Error",
portalClassName: portalClassName ? portalClassName : "Modal",
overlayClassName: overlayClassName ? overlayClassName : "Modal-overlay",
className: className ? className : "Modal-content",
shouldCloseOnOverlayClick: shouldCloseOnOverlayClick
? shouldCloseOnOverlayClick
: true,
shouldCloseOnEsc: shouldCloseOnEsc ? shouldCloseOnEsc : true,
content: content ? content : defaultContent
});
};
const closeModal = () => {
let stateCopy = { ...modalState };
stateCopy.isOpen = false;
setModalState(stateCopy);
};
const value = React.useMemo(() => [openModal, closeModal]);
return (
<ModalContext.Provider value={value} {...props}>
<>
{props.children}
<Modal
isOpen={modalState.isOpen}
onRequestClose={() => closeModal()}
contentLabel={modalState.contentLabel}
portalClassName={modalState.portalClassName}
overlayClassName={modalState.overlayClassName}
className={modalState.className}
shouldCloseOnOverlayClick={modalState.shouldCloseOnOverlayClick}
shouldCloseOnEsc={modalState.shouldCloseOnEsc}
>
{modalState.content}
</Modal>
</>
</ModalContext.Provider>
);
};
export { ModalProvider, useModal };
В компоненте, где я делаю запрос API, и он не работает, я хочу открыть модал через useModal
хук и передать функцию getSocialGroupData()
в качестве средства для перезагрузки компонента, нажав кнопку в модале без необходимость перезагрузить всю страницу, используя что-то вроде window.location.reload();
Вот пример компонента
import { useModal } from '../../contexts/ModalContext';
const Notes = () => {
const [openModal] = useModal();
const getSocialGroupData = (pNum, pSize, v) => {
// API call
notesService.getNotes((pNum != null ? pNum : 0), (pSize != null ? pSize : 10), (v ? v : view))
.then((response) => {
if (response.success === false) {
// When it fails, use the `useModal` hook and `openModal` function to open the modal
// I want to somehow call `getSocialGroupData` here, or something similar so that I do not have to reload the whole page
openModal();
}
...
});
}
useEffect(() => {
getSocialGroupData();
}, []);
return (
...
);
};
export default Notes;
Есть ли способ перезагрузить компонент из ModalProvider
без перезагрузки всей страницы?