Why am i getting “alertContext is undefined” in Alert.js component?
Alert.js
import React, { useContext } from "react";
import AlertContext from "../context/alert/alertContext";
const Alert = () => {
const alertContext = useContext(AlertContext);
const { alert } = alertContext;
return (
alert !== null && (
<div className={`w-full bg-${alert.type} px-4 py-2 mt-4 rounded `}>
<p className="text-white text-center font-mono">{alert.msg}</p>
</div>
)
);
};
export default Alert;
alertContext.js
import { createContext } from "react";
const alertContext = createContext();
export default alertContext;
AlertState.js
import React, { useReducer } from "react";
import AlertContext from "./alertContext";
import AlertReducer from "./alertReducer";
import { SET_ALERT, REMOVE_ALERT } from "../types";
const AlertState = (props) => {
const initialState = {
alert: null,
};
const [state, dispatch] = useReducer(AlertReducer, initialState);
//Set Alert
const setAlert = (msg, type) => {
dispatch({
type: SET_ALERT,
payload: { msg, type },
});
setTimeout(() => dispatch({ type: REMOVE_ALERT }), 5000);
};
return (
<AlertContext.Provider
value={{
alert: state.alert,
setAlert,
}}
>
{props.children}
</AlertContext.Provider>
);
};
export default AlertState;
alertReducer.js
import { SET_ALERT, REMOVE_ALERT } from "../types";
export default (state, action) => {
switch (action.type) {
case SET_ALERT:
return action.payload;
case REMOVE_ALERT:
return null;
default:
return state;
}
};
App.js
import React from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./components/Home";
import MovieInfo from "./components/MovieInfo";
import Alert from "./components/Alert";
import MovieState from "./context/movie/MovieState";
import AlertState from "./context/movie/MovieState";
function App() {
return (
<MovieState>
<AlertState>
<Router>
<div className="App">
<Navbar></Navbar>
<Alert></Alert>
<Switch>
<Route exact path="/" component={Home}></Route>
<Route exact path="/movie/:id" component={MovieInfo}></Route>
</Switch>
</div>
</Router>
</AlertState>
</MovieState>
);
}
export default App;