0% found this document useful (0 votes)
5 views13 pages

Dashboard Render Fix

The document outlines a React component for a dashboard that includes various functionalities such as user messaging, video suggestions, and event handling. It highlights issues with rendering errors in the browser, specifically mentioning a function error related to 'Destroy'. The code also includes styled components and hooks for managing state and side effects.

Uploaded by

toolsbot32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Dashboard Render Fix

The document outlines a React component for a dashboard that includes various functionalities such as user messaging, video suggestions, and event handling. It highlights issues with rendering errors in the browser, specifically mentioning a function error related to 'Destroy'. The code also includes styled components and hooks for managing state and side effects.

Uploaded by

toolsbot32
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Dashboard Render Fix

fix all error which prevent my dashbord page to render well in the browser , and this error in my
prowser console "Destroy " isn't a function this description don"t come of this script but when i run
it , it"s display in my browser please fix it also : import React, { memo, useCallback, useContext,
useEffect, useId, useLayoutEffect, useState } from 'react';
import Header from './Header'
import NavUser from "./NavUser"
import { Badge, Button, Checkbox, IconButton, Rating, TextareaAutosize, Tooltip } from
'@mui/material'
import styled from 'styled-components';
import EventNoteRoundedIcon from '@mui/icons-material/EventNoteRounded';
import AccessTimeRoundedIcon from '@mui/icons-material/AccessTimeRounded';
import VideoLibraryRoundedIcon from '@mui/icons-material/VideoLibraryRounded';
import KeyboardArrowRightOutlinedIcon from '@mui/icons-material/KeyboardArrowRightOutlined';
import CancelOutlinedIcon from '@mui/icons-material/CancelOutlined';
import ThumbsUpDownRoundedIcon from '@mui/icons-material/ThumbsUpDownRounded';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline';
import toast from 'react-hot-toast'
import DialogBox from './DialogBox';
import DisclaimerText from "./DisclaimerText";
import VideoThumbnail from './VideoThumbnail';
import ArticleContent from "../ArticleComponents/ArticleContent"
import { BsArrowUpRight, BsCheckCircle, BsCheckCircleFill, BsChevronRight, BsCircle, BsCircleFill,
BsEnvelope, BsFillArchiveFill, BsFillRocketTakeoffFill, BsRocket, BsRocketFill, BsRocketTakeoff } from
'react-icons/bs';
import ThemeHandler, { ThemeContext } from './ThemeHandler';
import { useMutation, useQueries, useQuery } from '@tanstack/react-query';
import apiClient from '../axios_handling/ApiClient';
import Loader from './Loader';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/useAuthStore'
import { MessageCircleMoreIcon } from 'lucide-react';
import ChatContainer from '../RealChat/components/ChatContainer';
import { useChatStore } from '../../src_1/store/useChatStore';
import { useForm } from 'react-hook-form';

const para = `Lorem ipsum dolor sit amet consectetur adipisicing elit. Laudantium asperiores
laborum repudiandae quidem eligendi suscipit quaerat iusto a, officiis, deleniti impedit magnam,
vero rerum voluptas? Possimus voluptatum doloribus expedita est.`;

const ProgressBar = styled.div`


` position: relative;
width: 100%;
background: #C7D0DD;
height: 10px;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/13
border-radius: 4px;
overflow: hidden;
z-index: 5;

&::before {
content: '';
z-index: -1;
position: absolute;
height: 100%;
background: conic-gradient(#0f0f ,3.6deg, #0f0f 0deg);
transition: .5s ease-in-out;
top: 0;
left: 0;
height: 100%;
width: ${props => props.width || '0%'};
}
`;
`
function Dashboad() {
const [UserName, setUserName] = useState("Junior");
const [token, setToken] = useState(0);
const [SkillsLength, setSkillsLength] = useState(0);
const [RatingView, setRatingView] = useState(false);
const [showDialog, setShowDialog] = useState(false);
const [showMessage, setshowMessage] = useState(false);

const { messages: Chats } = useChatStore();

const { sendMessage } = useChatStore()


const MessageForm = useForm()

const [MediaQuery, setMediaQuery] = useState(false)


const [RatingValue, seRatingValue] = useState(0)

const SendMessage = async (data) => {


try {

await sendMessage({
text: data.text.trim()
});
MessageForm.reset()
} catch (error) {
toast.error("Failed to send message");
}
}
const SwitchMedia = () => {
setMediaQuery(!MediaQuery)
}
const OpenMessage = () => {
setshowMessage(!showMessage)
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/13
const OpenDisclaimer = () => {
setShowDialog(!showDialog);
}
const { isDarkMode, toggleTheme } = ThemeContext
const Playlists = []
const Videos=[
{
useFulLinks: [
{ title: "Youtube", link: "www.youtube.com/feed/downloads" },
{ title: "Youtube", link: "www.youtube.com/feed/downloads" },
{ title: "Youtube", link: "www.youtube.com/feed/downloads" }
],
theme: "Hacking",
title: "Introduction au Hacking",
level: "Débutant",
tag: "",
link: 'https://www.youtube.com/watch?v=lTRiuFIWV54',
thumbnail: "https://img.youtube.com/vi/lTRiuFIWV54/hqdefault.jpg",
childrenVideo: (<><ArticleContent content={para} label={"Yann"}></ArticleContent> </>)
},
{
theme: "Sécurité Réseaux",
title: "Sécurité des Réseaux",
level: "Intermédiaire",
tag: "",
link: 'https://www.youtube.com/watch?v=8q5mc1AEtYo',
thumbnail: "https://img.youtube.com/vi/8q5mc1AEtYo/hqdefault.jpg",
childrenVideo: (<><ArticleContent content={para} label={"VONVON"}></ArticleContent> </>)
},
{
theme: "Cryptographie",
title: "Bases de la Cryptographie",
level: "Avancé",
tag: "",
link: "https://www.youtube.com/watch?v=5qap5aO4i9A",
thumbnail: "https://img.youtube.com/vi/5qap5aO4i9A/hqdefault.jpg",
childrenVideo: (<><p>Yann Ubarne</p></>)
},
];

// const {
// data: EventData,
// isLoading: EventLoading,
// isError: isEventError,
// error: EventError,
// } = useQuery({
// queryFn: async () => {
// const { data } = await apiClient.get('/api/user/events');
// return data
// },
// queryKey: ["New_Event"],
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/13
// refetchInterval: 1000,
// enabled: truehorloge,
// staleTime: 1,
// });

const { authUser, checkAuth } = useAuthStore()

useEffect(() => {
checkAuth()
console.log(authUser)

const { username = '', token = 0, skillsLength = 0 } = authUser || {}


setUserName(username);
setToken(token);
setSkillsLength(skillsLength)

}, [checkAuth,authUser]);

// useEffect(() => {
// if (isEventError) {
// console.error( EventError?.message);
// }
// }, [ isEventError, EventError])

const Events =[] //EventData?.result

// console.log(Events)

// if (EventLoading) {
// return <Loader />;
// }
// console.log(Events)
return (
<ThemeHandler>
<>
<Header MediaQuery={MediaQuery}></Header>
<div className="dashboard-parent">
<div className="dashboard">
<div className="dashboard-content">
<DashboardHeader UserName={UserName} OpenDisclaimer={OpenDisclaimer} />
<DashboardSecondPart token={token} SkillsLength={SkillsLength} ProgressBar=
{ProgressBar} />
<UserRequest SendMessage={SendMessage} Chats={Chats} OpenMessage={OpenMessage}
MessageForm={MessageForm}/>
<EventHandling Events={Events} />
<VideoSuggestion Videos={Videos} />
<RatingBtn setRatingView={setRatingView} />
</div>
</div>
<RatingHandling
RatingView={RatingView}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/13
setRatingView={setRatingView}
seRatingValue={seRatingValue}
RatingValue={RatingValue}
/>
</div>
<DialogBox show={showMessage} onClose={OpenMessage} title={"Messages"} content={
<div style={{height:'100%'}}>
<div id='user-chat-bg' style={{ display: "flex",alignItems: "center",justifyContent: "center"}}>
<div style={{borderRadius: "0.5rem",width: "100%",maxWidth: "72rem",height: "calc(100vh -
8rem /* 128px */)"}} >
<div style={{display: "flex",height: "100%",borderRadius: "0.5rem",overflow: "hidden"}}>
<ChatContainer />
</div>
</div>
</div>
</div>
} />
<DialogBox
show={showDialog}
onClose={OpenDisclaimer}
title={"Disclaimer"}
content={<DisclaimerText />}
/>
<NavUser
SwitchMedia={SwitchMedia}
// User={User}
/>
<Loader />
</>
</ThemeHandler>
);
};

export default Dashboad;

const DashboardHeader = memo(({ UserName, OpenDisclaimer }) => (


<div className="first-part-dashboard">
<div className="first-part-first-child">
<div className="user-logo"></div>
<p className='greetings-user'>Salut <span className='user-name-dashbord'>{UserName}
</span> 👋 </p>
</div>
<div className="first-part-last-child">
<Button
onClick={OpenDisclaimer}
variant='contained'
className='disclaimer'
>Disclaimer</Button>
</div>
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/13
</div>
));

const DashboardSecondPart = memo(({ SkillsLength, token, ProgressBar }) => (


<div className="two-part-dashboard">
<UserProgress SkillsLength={SkillsLength} ProgressBar={ProgressBar} />
<UserTokens token={token} />
</div>
));

const UserTokens = memo(({ token }) => (


<div className="two-part-last-child">
<div className="ask-counter">
<div className="ask-counter-header">
<h3>Points </h3>
<BsCheckCircle className='card_icon' />
</div>
<p>{token}</p>
</div>
</div>
));

const UserProgress = memo(({ SkillsLength, ProgressBar }) => (


<div className="two-part-first-child">
<div className="progress-user">
<div className="progress-user-header">
<h3>Progression</h3>
<BsRocketTakeoff className='card_icon' />
</div>
<div className="progress-handler">
<ProgressBar width={SkillsLength * 0.5 + '%'}></ProgressBar>
<p className='progress-length'>{SkillsLength * 0.5}%</p>
</div>
</div>
</div>
));

const UserRequest = memo(({ Chats, OpenMessage,MessageForm,SendMessage }) => (

<div className="three-part-dashboard">
<form action="" className="ask-form">
<TextareaAutosize
{...MessageForm.register('text',{required:true})}
className='ask-user-area'
aria-label="minimum height"
minRows={5}
placeholder="Posez moi vos questions" />
<div className="ask-btn-handler">
<Button variant='contained' className='send-ask' onClick=
{MessageForm.handleSubmit(SendMessage)}>Envoyer</Button>
{Chats.length > 0 && <Tooltip title="Nouveau Message">
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/13
<IconButton color='inherit' onClick={OpenMessage}>
<Badge badgeContent={Chats.length} max={9} color='error'>
<MessageCircleMoreIcon className='new-message' />
</Badge>
</IconButton>
</Tooltip>}
<Tooltip title="Vos questions sont répondu dans un délai de moins de 24h, PS: Si le système
détecte des spams votre adresse IP sera bloquer">
<ErrorOutlineIcon className='warning-spam-and-more'></ErrorOutlineIcon>
</Tooltip>
</div>
</form>
</div>
));

const EventHandling = memo(({ Events }) => (


<div className="even-coming-up-area">
<div className="header-event-content">
<h3 className="event-title-header">évènement à venir</h3>
<EventNoteRoundedIcon />
</div>
<div className={`all-events ${Events?.length > 2 ? "add-scroll" : ""}`}>
<ul className="event-content">
{Events?.length === 0 ? <h3 className='not-content'>Événement indisponible</h3> :
Events?.map((event, index) => (
<li key={index}>
<p className='event-title'>{event?.title}</p>
<div className="handle-event">
<AccessTimeRoundedIcon className='hours-icon' />
<p className="event-date-and-hours">{event?.date}</p><span className="barre-
between">|</span>
<p className="event-level">Niveau : {event?.level}</p>
</div>
</li>
))}
</ul>
</div>
</div>
));

const VideoSuggestion = memo(({ Videos }) => (


<div className="suggestions-some-video-area">
<div className="suggestions-header">
<h3 className="suggestions-title">Recommandations</h3>
<VideoLibraryRoundedIcon />
</div>
<div className={`handle-contenu ${Videos?.length > 3 ? "add-scroll-x" : ""}`}>
{Videos?.length === 0 ? <h3 className='not-content'>Recommandations indisponible</h3> :
<ul className="video-recommandation-container">
{Videos?.map((tutorial, index) => (
<li key={index}>
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/13
<VideoThumbnail
thumbnail={tutorial?.thumbnail}
childrenVideo={tutorial?.childrenVideo}
PlaylistTitle={"JUNIOR test"}
Playlist={Videos}
SingleVideo={false}
link={tutorial?.link}
isDarkMode={true}
title={tutorial?.title}
theme={tutorial?.theme}
level={tutorial?.level}

/>
</li>
))}
{/* {Videos?.map((tutorial, index) => (
<li key={index}>
<VideoThumbnail
thumbnail={tutorial?.thumbnail}
childrenVideo={tutorial?.childrenVideo}
link={tutorial?.link}
title={tutorial?.title}
theme={tutorial?.theme}
level={tutorial?.level}
/>
</li>
))} */}
</ul>
}
</div>
</div>
));

const RatingBtn = memo(({ setRatingView }) => (


<div className="rating-hacking-focus-area">
<Button
onClick={() => setRatingView(true)}
variant='contained'
>Notez Hacking Focus <ThumbsUpDownRoundedIcon className='rating-icon' />
</Button>
</div>
));

const RatingHandling = memo(({ RatingView, setRatingView, seRatingValue, RatingValue }) => (


<div className={RatingView ? "rating-parent set-rating-property" : "rating-parent"}>
<KeyboardArrowRightOutlinedIcon className={RatingView ? 'sharp-open-rating sharp-open-
rating-set-display' : "sharp-open-rating"} onClick={() => setRatingView(true)} />
<CancelOutlinedIcon className={RatingView ? "cancel-rating-area-view" : "cancel-rating-area-
hidden"} onClick={() => { setRatingView(false); seRatingValue(0) }} />
<div className={RatingView ? "rating-content set-rating-content" : 'rating-content'}>
<UserRate RatingValue={RatingValue} seRatingValue={seRatingValue} />
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/13
<RateForm RatingValue={RatingValue} setRatingView={setRatingView} seRatingValue=
{seRatingValue} />
<div className={RatingValue >= 9 ? "trustpilot-review trustpilot-review-view" : 'trustpilot-
review'}>
<h4 className='trustpilot-sentence'>Que diriez vous d'une note sur Trustpilot</h4>
<p className='trustpilot-sentence'>Votre avis nous est précieux. Si vous avez quelques
minutes, laissez nous un avis sur </p>
<div className="trustpilot-action">
<Button variant='contained' onClick={() => window.open('https://www.facebook.com', '_blank',
'noopener,noreferrer')}>TrustPilot</Button>
<Button variant='contained' onClick={() => { setRatingView(false); seRatingValue(0) }}>Non
merci</Button>
</div>
</div>
</div>
</div>
));

const RateForm = memo(({ RatingValue, setRatingView, seRatingValue }) => (


<form className={RatingValue < 9 && RatingValue !== 0 ? "review-user review-user-view" : 'review-
user'}>
<FormArea />
<div className="review-btns">
<Button variant='contained' onClick={() => { setRatingView(false); seRatingValue(0) }}>Non
Merci</Button>
<Button variant='contained'>Envoyer</Button>
</div>
</form>
));

const FormArea = memo(() => (


<textarea
id="review"
cols="25"
rows="5"
placeholder='Merci beaucoup ! Pourriez-vous nous suggérer quelques améliorer ?'></textarea>
));

const UserRate = memo(({ RatingValue, seRatingValue }) => (


<div className={RatingValue !== 0 ? "rating-user-hidden" : "rating-use"} style={{ overflow: "hidden"
}}>
<p className='probability-text'>Qu'elle est la probabilité que vous recommandez Hacking Focus à
vos connaissances passionné par ce monde du Hacking Éthique ?</p>
<Rating name="customized-10" defaultValue={0} max={10} className='rating' onChange={(value)
=> seRatingValue(value.target.value)} />
<div className="probaility-name">
<p>Peu probable</p>
<p>Très probable</p>
</div>
</div>
));
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/13
{/* <div className="h-full bg-base-200">
<div className="flex items-center justify-center">
<div className="bg-base-100 rounded-lg shadow-cl w-full max-w-6xl h-[calc(100vh-8rem)]">
<div className="flex h-full rounded-lg overflow-hidden">
<ChatContainer />
</div>
</div>
</div>
</div> */}

The code you provided is quite comprehensive but contains multiple issues that need fixing. Here's how
to address the key problems, including the "Destroy" is not a function error:

Steps to Resolve Issues:

1. `Destroy` Error in Console:


The error indicates that somewhere in your code, a function named `Destroy` is being called,
but it is either undefined or not a function.
Check all third-party libraries and components (e.g., `react-hot-toast`, `@tanstack/react-
query`, `react-router-dom`, etc.) to ensure they are correctly imported and initialized.
Look for any `useEffect` cleanup functions or event listeners that might reference `Destroy`.
Replace `Destroy` with the proper cleanup logic or remove unnecessary listeners.
2. Theme Context Misuse:
Replace `const { isDarkMode, toggleTheme } = ThemeContext` with the `useContext` hook:

jsx

const { isDarkMode, toggleTheme } = useContext(ThemeContext);

3. Error Handling with `useQuery` and `useMutation`:


Ensure `apiClient` is correctly configured with base URLs and interceptors.
Uncomment the `useQuery` logic and handle the states properly:

jsx

const {
data: EventData,
isLoading: EventLoading,
isError: isEventError,
error: EventError,
} = useQuery({
queryFn: async () => {
const { data } = await apiClient.get('/api/user/events');
return data;
},
queryKey: ["New_Event"],
refetchInterval: 1000,
});

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/13
4. Handle Missing Styles:
Ensure all class names (e.g., `.dashboard-parent`, `.dashboard-content`) are styled in your CSS
or styled-components.
5. Chat Store State:
Verify the `useChatStore` implementation. Ensure the `sendMessage` and `messages` properties
are correctly defined and used:

jsx

const { messages: Chats, sendMessage } = useChatStore();

6. Progress Bar Gradient Issue:


Replace the `background` of the `ProgressBar` with a valid CSS gradient:

jsx

background: linear-gradient(90deg, #0f0, #f00);

7. Event and Video List Rendering:


Use optional chaining (`?.`) to prevent rendering errors when the data is undefined or null.
Simplify the rendering of `Videos` and `Events` by using early returns for empty states.
8. Refactor `Dashboad` Component for Clarity:
Extract the large JSX into smaller, reusable components. For example, `DashboardHeader`,
`DashboardSecondPart`, and `UserRequest` are already defined.
9. Fix Imports:
Ensure all imports are valid and the corresponding components (`Header`, `NavUser`, etc.)
exist.

Here’s the updated `Dashboad` component after addressing the issues:

Updated Code

jsx

import React, { memo, useContext, useEffect, useState } from 'react';


import { useForm } from 'react-hook-form';
import styled from 'styled-components';
import toast from 'react-hot-toast';
import { useQuery } from '@tanstack/react-query';
import apiClient from '../axios_handling/ApiClient';
import Header from './Header';
import NavUser from './NavUser';
import DialogBox from './DialogBox';
import { ThemeContext } from './ThemeHandler';
import Loader from './Loader';
import ChatContainer from '../RealChat/components/ChatContainer';
import DisclaimerText from './DisclaimerText';
import VideoThumbnail from './VideoThumbnail';
import { useChatStore } from '../store/useChatStore';

const ProgressBar = styled.div`


position: relative;

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/13
width: 100%;
background: #c7d0dd;
height: 10px;
border-radius: 4px;
overflow: hidden;

&::before {
content: '';
position: absolute;
height: 100%;
background: linear-gradient(90deg, #0f0, #f00);
width: ${(props) => props.width || '0%'};
transition: 0.5s ease-in-out;
}
`;

function Dashboad() {
const { authUser, checkAuth } = useAuthStore();
const { messages: Chats, sendMessage } = useChatStore();
const { register, handleSubmit, reset } = useForm();
const { isDarkMode } = useContext(ThemeContext);

const [UserName, setUserName] = useState('');


const [token, setToken] = useState(0);
const [SkillsLength, setSkillsLength] = useState(0);
const [showDialog, setShowDialog] = useState(false);

useEffect(() => {
checkAuth();
if (authUser) {
const { username, token, skillsLength } = authUser;
setUserName(username || '');
setToken(token || 0);
setSkillsLength(skillsLength || 0);
}
}, [authUser, checkAuth]);

const handleSendMessage = async (data) => {


try {
await sendMessage({ text: data.text.trim() });
reset();
} catch (error) {
toast.error('Failed to send message');
}
};

const { data: EventData, isLoading: EventLoading } = useQuery(


['New_Event'],
async () => {
const { data } = await apiClient.get('/api/user/events');
return data;
}
);

if (EventLoading) return <Loader />;

return (
<div className={`dashboard ${isDarkMode ? 'dark-mode' : ''}`}>
<Header />
<DialogBox
show={showDialog}
onClose={() => setShowDialog(false)}
title="Disclaimer"
content={<DisclaimerText />}
/>
<NavUser />
<form onSubmit={handleSubmit(handleSendMessage)}>
<textarea {...register('text')} />
<button type="submit">Send</button>
</form>
<ProgressBar width={`${SkillsLength * 0.5}%`} />
<ChatContainer Chats={Chats} />
</div>
);
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/13
export default Dashboad;

Next Steps:

Test the updated component.


Ensure all dependencies are installed.
Verify the styling and functionality of nested components.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/13

You might also like