ํ์ฌ ๋ด์ฉ์ ์ ๋ ฅํด์ฃผ์ธ์ ๋ฉ์ธ์ง๊ฐ ์ถ๋ ฅ๋๋ ํด๋น Alert์ ์ปจํ ์คํธ๋ก ๋ง๋ค์ด๋ณด๊ฒ ์.


AlertReducer.js
function AlertReducer(state, action) {
switch (action.type) {
case "SET_ALERT":
return action.payload;
case "REMOVE_ALERT":
return null;
default:
return state;
}
}
export default AlertReducer;
AlertContext.jsx
import { createContext, useReducer } from "react";
import AlertReducer from "./AlertReducer";
const AlertContext = createContext();
export const AlertProvider = ({ children }) => {
const initialState = null;
//๋ฌธ์์ด ๊ฒฝ๊ณ ์ฐฝ ๋ด์ฉ
const [state, dispatch] = useReducer(AlertReducer, initialState);
//๊ฒฝ๊ณ ์ฐฝ ๋ฉ์ธ์ง๋ฅผ ์ค์ ํ๊ณ 3์ด๋ค ์ ๊ฑฐํจ
//msg => ๋ฉ์ธ์ง type=> AlertReducer์ ์ง์ ํ ํ์
const setAlert = (msg, type) => {
dispatch({
type: "SET_ALERT",
payload: { msg: msg, type: type }, // {msg,type}์ผ๋ก ์๋ต๊ฐ๋ฅํจ
});
setTimeout(() => dispatch({ type: " REMOVE_ALERT" }), 3000);
};
return (
<AlertContext.Provider
value={{
alert: state,
setAlert,
}}
>
{children}
</AlertContext.Provider>
);
};
export default AlertContext;
state์๋ ๊ฒฝ๊ณ ์ฐฝ์ ์ถ๋ ฅ๋ ๋ฉ์ธ์ง์ ํ์ฌ ํ์ ์ ๊ฐ์ง๊ณ ์์.
์ด ํ๋ก๋ฐ์ด๋๋ฅผ ์ ์ฉํ๋ฉด ๋จ
main.jsx

UserSearch.jsx์์ ์ ์ฉํ๊ธฐ



3์ด๋ค์ ์ฌ๋ผ์ง๋์ง ํ์ธํ๊ธฐ


import React, { useContext } from "react";
import AlertContext from "../../context/alert/AlertContext";
const Alert = () => {
const { alert } = useContext(AlertContext);
return (
alert !== null && (
<p className="flex items-start mb-2 space-x-2">
<span>๐</span>
<span className="flex-1 text-base font-semibold leading-7">
<strong>{alert.msg}</strong>
</span>
</p>
)
);
};
export default Alert;
App.jsx

ํ ์คํธํ๊ธฐ
๊ฒ์์ฐฝ์ ์๋ฌด๋ฐ ์ ๋ ฅ์ ํ์ง์๊ณ Go๋ฒํผ์ ๋๋ฅผ ๊ฒฝ์ฐ
๋ด์ฉ์ ์ ๋ ฅํด์ฃผ์ธ์ ์ถ๋ ฅํ๊ณ 3์ด๋ค์ ์ฌ๋ผ์ง

