Home > database >  Object is undefined when trying to fetch it using useContext()
Object is undefined when trying to fetch it using useContext()

Time:10-29

I am very new to React and was trying to make a context in React so that in my notes app such that I can trigger my custom made alert for relevant user activity but when I am trying to use the values from the context using useContext I am getting error : "Cannot destructure property 'alert' of 'Object(...)(...)' as it is undefined."

Here's the code:-

Creating Context

import React from 'react';

const AlertContext = React.createContext(null);

export default AlertContext;

Populating Value to the Context

import React,{useState} from 'react';
import AlertContext from "./AlertContext";

const ShowAlert = (props)=>{
    const [alert,setAlert] = useState(null);

    const showAlert = (message,type)=>{
            setAlert({
                msg:message,
                type:type
            })
            setTimeout(()=>{
                setAlert(null);
            },3000);
    }

    return(
        <AlertContext.Provider value={{alert,showAlert}}>
            {props.children}
        </AlertContext.Provider>
    )
}

export default ShowAlert;

Trying to use the values

import React, { useContext } from "react";
import { Navbar, Button, Nav } from "react-bootstrap";
import { Link, useHistory } from "react-router-dom";
import ShowAlert from "../contexts/ShowAlert";
import MyAlert from "./MyAlert";

function Header() {

  const {alert} = useContext(ShowAlert);

  let history = useHistory();

  const handleLogout = () => {
    localStorage.removeItem("token");
    history.push("/login");
  };

  return (
    <>
    <header>
      <Navbar collapseOnSelect expand="lg" className="header">
        <Navbar.Brand className="heading">
          <Link to="/" className="headerLink">
            Note Cloud
          </Link>
          <i className="fas fa-cloud-upload-alt cloudIcon"></i>
        </Navbar.Brand>
        <Navbar.Toggle aria-controls="responsive-navbar-nav" />
        <Navbar.Collapse id="responsive-navbar-nav">
          <Nav className="me-auto"></Nav>
          {localStorage.getItem("token") && (
            <Nav>
              <Nav.Link>
                <Button variant="primary" size="lg" onClick={handleLogout}>
                  Logout
                </Button>
              </Nav.Link>
            </Nav>
          )}
        </Navbar.Collapse>
      </Navbar>
    </header>
   <MyAlert alert={alert}></MyAlert>
    </>
  );
}

export default Header;

Error That I am getting enter image description here

enter image description here

CodePudding user response:

Try doing the Context like this instead of null.

import React from "react";

const AlertContext = React.createContext({
  alert: {},
  setAlert: (alert) => {},
});

export default 

CodePudding user response:

i think your export is the fail

export const  AlertContext = React.createContext({})

or as well you can try:

< AlertContext.Consumer>
    {(context) => {
      console.log(context)
    }}
  </AlertContext.Consumer>
  • Related