Sushanth
Sushanth

Reputation: 15

Not able to access react state using Context API

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

Upvotes: 0

Views: 816

Answers (2)

user22340374
user22340374

Reputation: 1

Add the following check in your Alert component beacuse initially the 'alerts' object is going to be null. That's why it is giving this error. Adding this check will resolve the error.

import React, { useContext } from "react";
import AlertContext from "../context/AlertContext";

const Alert = () => {
  const {alerts} = useContext(AlertContext);

  return alerts !== null ? (
    <div
      className={`alert alert-${alerts.type} alert-dismissible fade show`}
      role="alert"
    >
      {alerts.message}
    </div>
  ) : (
    <></>
  );
};

export default Alert;

Upvotes: 0

Vida Hedayati
Vida Hedayati

Reputation: 336

Try it

<AlertContext.Provider value={{setMsg,alerts}}>
         {props.children}
     </AlertContext.Provider>

Upvotes: 2

Related Questions