I want to create a global modal component using redux/toolkit
and manage it globally. When I click the drop-down menu, I create the message I want to display the modal, and when I click the Ok or Cancel button and background, I try to close it.
There is no problem with the event to open the modal, but to close it, send the following error.
Attached is the contents checked according to the error message.
-
pacakge.json:
"react": "^18.2.0", "react-copy-to-clipboard": "^5.1.0", "react-dom": "^18.2.0",
-
modalSlice.js
import { createSlice } from '@reduxjs/toolkit' const initialState = { modalContent: '', isOpen: false, } export const modalSlice = createSlice({ name: 'modal', initialState, reducers: { openModal: (state, actions) => { const { modalContent } = actions.payload const updateState = { ...state, isOpen: true, modalContent, } return updateState }, closeModal: (state, actions) => { console.log(actions) const updateState = { ...initialState, } return updateState }, }, }) export const { openModal, closeModal } = modalSlice.actions export default modalSlice.reducer
Modal.js
const Modal = () => { const dispatch = useDispatch const { modalContent } = useSelector((state) => state.modal) const modalHandler = (e) => { dispatch(closeModal) } return ( <> <ModalContainer> <ModalBack onClick={modalHandler} /> <ModalContentWrapper> <ModalContent>{modalContent}</ModalContent> <ModalBtnWrapper> <ModalBtn onClick={modalHandler}>취소</ModalBtn> <ModalBtn onClick={modalHandler}>확인</ModalBtn> </ModalBtnWrapper> </ModalContentWrapper> </ModalContainer> </> ) }
-
npm ls react
[email protected] /Users/mary/231014 wedding/mobile/wedding_reception ├─┬ @fortawesome/[email protected] │ └── [email protected] deduped ├─┬ @reduxjs/[email protected] │ └── [email protected] deduped ├─┬ @testing-library/[email protected] │ └── [email protected] deduped ├─┬ [email protected] │ └── [email protected] deduped ├─┬ [email protected] │ └── [email protected] deduped ├─┬ [email protected] │ ├── [email protected] deduped │ └─┬ [email protected] │ └── [email protected] deduped ├─┬ [email protected] │ ├─┬ [email protected] │ │ └── [email protected] deduped │ └── [email protected] deduped ├─┬ [email protected] │ └── [email protected] deduped ├── [email protected] └─┬ [email protected] └── [email protected] deduped
2
Answers
Invalid Hook Call Warning
You might be breaking the Rules of Hooks.
it should be written like that
Issue
At first it seems odd how not calling
useDispatch
could cause an "invalid hook call" error. In the code you have saved a reference to theuseDispatch
hook function and named itdispatch
, and then later called this function in a nested callback function which is clearly a violations of the Rules of Hooks.Solution
Invoke the
useDispatch
function correctly at the top level so the actualdispatch
function is callable in a callback function.