I am trying to add alert component to my notebook App so when user logins and make any changes he gets alert at the top, To execute this I used context API, but when I am trying to access the state object to Alert component from AlertContext file, I get this below error
alert.js:10 Uncaught TypeError: Cannot read properties of undefined (reading 'type')
Here is my Alert and AlertContext files
import React from "react";
import { useContext } from "react";
import { AlertContext } from "../context/notes/AlertContext";
export const Alert = (props) => {
const { alerts } = useContext(AlertContext);
return (
<div>
<div
className={`alert alert-${alerts.type} alert-dismissible fade show`}
role="alert"
role="alert"
>
{alerts.message}
</div>
</div>
);
};
import React, { useState } from 'react'
import { AlertContext } from './AlertContext'
const AlertState = (props) => {
const [alerts, setAlerts] = useState({ message: null, type: null });
const setMsg = (msg,type) =>
{
setAlerts({ message: msg, type: type });
setTimeout(() =>
{
setAlerts({ message: null, type: null })
},1500);
}
return (
<AlertContext.Provider value={setMsg , alerts}>
{props.children}
</AlertContext.Provider>
);
}
export default AlertState
Alertcomponent within your provider, in this case theAlertStatecomponent?<AlertContext.Provider value={setMsg , alerts}>, it's supposed to be<AlertContext.Provider value={{setMsg , alerts}}>Alertcomponent) to be able to use React context, it has to have theProvideras its parent (in your caseAlertContext.Provider, or more specifically yourAlertStatecomponent). I mean do you have something like this in your component hierarchy:<AlertState><Alert /></AlertState>?