2

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;

Edit:- MyAlert Component

import React, { useContext } from "react";
import { Alert } from "react-bootstrap";
import ShowAlert from "../contexts/ShowAlert";

const MyAlert = (props) => {
  
  const {alert} = useContext(ShowAlert);
  const capitalize = (word) => {
    if(word==="danger")
    {
      word = "error";
    }
    const lower = word.toLowerCase();
    return lower.charAt(0).toUpperCase() + lower.slice(1);
  };
  return (
    <div style={{ height: "50px" , width:"100%"}}>
      {alert && (
        <Alert
          variant={alert.type}
        >
          <Alert.Heading>{capitalize(alert.type)}</Alert.Heading>
          <p>{capitalize(alert.msg)}</p>
        </Alert>
      )}
    </div>
  );
};

export default MyAlert;

Error That I am getting enter image description here

enter image description here

Tushar Verma
  • 163
  • 1
  • 9

2 Answers2

1

Try doing the Context like this instead of null.

import React from "react";

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

export default 
demiglace
  • 405
  • 1
  • 5
  • 12
  • thanks for the reply I tried it this way but same error persists, I have added the code of my MyAlert Component which is my final goal to implement if you could suggest any other way of doing that would also be very helpful – Tushar Verma Oct 29 '21 at 07:31
0

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>
rnewed_user
  • 1,386
  • 7
  • 13
  • @m3w thanks for the reply I tried it this way(the first one by correcting my export) but same error persists. – Tushar Verma Oct 29 '21 at 07:17
  • @m3w I have added the code of my MyAlert Component which is my final goal to implement if you could suggest any other way of doing that would also be very helpful – Tushar Verma Oct 29 '21 at 07:32