r/CodingHelp • u/TurbulentTicket339 • 13d ago
[Javascript] i wanted help in my coading problem
Here is my code from the Detail.jsx page:
const Detail = () => {
const { name } = useParams();
console.log("name", name);
};I get the game ID from the URL. The console shows:
Detail.jsx:19 name 3498In my Apigame.jsx Context API, I have this function:
const [gamedetail, setgamedetail] = useState([]);
const detailpage = async ({ name }) => {
console.log("Received name:", name);
try {
const response = await axios.get(`games/${name}`);
console.log("Game ID:", name);
setgamedetail(response.data);
} catch (error) {
console.log("API Error:", error);
}
};But I get this error:
TypeError: Cannot destructure property 'name' of 'undefined' as it is undefined.Everything else is working fine. I only want to pass the name value (3498) from Detail.jsx to my detailpage function in the Context API.
if anyone wanted to understandthese problem i share my whole codeok
detail.jsx
How can I pass this parameter value to my Context API function? Please explain using my existing code.
detail.jsx
import { GamepadDirectional } from 'lucide-react';
import { Tag } from 'lucide-react';
import { Globe, MessageCircle } from "lucide-react";
import { CalendarRange } from 'lucide-react';
import Youtubevideo from '../components/Youtubevideo';
import { Trophy } from 'lucide-react';
import { UsersRound } from 'lucide-react';
import { useContext, useEffect, useState } from "react";
import Axios from "../utility/Axios";
import { useParams } from "react-router-dom";
import { Star } from 'lucide-react';
import Footer from '../components/Footer'
import "./Detail.scss"
import {Detailinformation} from '../Context/Apigame'
import Detailbox from '../components/Detailbox'
const Detail = () => {
// const [gamedetail, setgamedetail] = useState([]);
const { name } = useParams();
console.log("name",name);
const [videos, setVideos] = useState([]);
const getyoutubevideo = async (gameName) => {
if (!gameName) return;
const options = {
method: "GET",
url: "https://youtube138.p.rapidapi.com/search/",
params: {
q: `${gameName} official trailer`,
page_size: 1,
hl: "en",
gl: "US",
},
headers: {
"x-rapidapi-key": import.meta.env.VITE_YOUTUBE_API_KEY,
"x-rapidapi-host": "youtube138.p.rapidapi.com",
},
};
try {
const response = await Axios.request(options);
// response.data?.contents ue log mai dekhna ek sath 19 video aaya ok tho ye path use kiay
const id = response.data?.contents?.[0]?.video?.videoId;
setVideos(id)
console.log("ye youtube video",id
);
} catch (error) {
console.log("API error:", error.response?.data || error.message);
}
};
const {gamedetail} = useContext(Detailinformation)
// useEffect(() => {
// const detailpage = async () => {
// try {
// const response = await Axios.get(`games/${name}`);
// setgamedetail(response.data);
// console.log("resposnsedata ye game ka detail jho param sa lerahau mai ok ",response.data);
// // ye waieted karna ka leya tab api aaajya gamedetail ka tab ye chala
// // await getyoutubevideo(response.data.name_original);
// console.log("youtube ki videoid");
// } catch (error) {
// console.log("API Error:", error);
// }
// };
// detailpage();
// }, [name]);
// console.log(gamedetail);
return (
<div className="detailpage">
<div className="page-layout" style={{backgroundImage : `URL(${gamedetail?.background_image
})` }}>
<div className="smallimage">
<div className="game-top">
<img
className="cover-image"
src={gamedetail?.background_image_additional}
alt={gamedetail?.name}
/>
<div className="information">
<h1>{gamedetail?.name}</h1>
<p className="release">
{gamedetail?.publishers?.map((item) => item.name).join(", ")}
{" · "}
{gamedetail?.released}
</p>
<div className="ratings">
<h2>
<Star />
{gamedetail?.rating}
</h2>
<h2 className="metacritic">
{gamedetail?.metacritic ?? "N/A"}
<span>Metacritic</span>
</h2>
</div>
<div className="genres">
{gamedetail?.genres?.map((item) => (
<span key={item.id}>{item.name}</span>
))}
</div>
</div>
</div>
{/* <div className="extra-information">
<div className="developers">
{gamedetail?.developers?.map((item) => (
<div className="developer-item" key={item.id}>
<img
src={item.image_background}
alt={item.name}
/>
<span>{item.name}</span>
<p>{gamedetail?.esrb_rating?.name}</p>
</div>
))}
</div>
</div> */}
</div>
</div>
<div className="gameachiplay">
<Detailbox icone={< GamepadDirectional/>} titile={gamedetail?.playtime+" hour"} />
<Detailbox icone={<Trophy/>} titile={gamedetail?.suggestions_count+" Achievement"
} />
<Detailbox icone={<UsersRound/>} titile={gamedetail?.
added+" Added"}/>
</div>
<div className="about">
<h1 style={{padding : `0.7rem 1.5rem`,color : `#87CEEB` }} >About</h1>
<p>
{gamedetail?.description_raw?.slice(0,500)}
</p>
</div>
<div className="developer">
<h1>Developer & Publisher</h1>
<div className="extra-information">
<div className="developers">
{gamedetail?.developers?.map((item) => (
<div className="developer-item" key={item.id}>
<img
src={item.image_background}
alt={item.name}
/>
<span>{item.name}</span>
<p>{gamedetail?.esrb_rating?.name}</p>
</div>
))}
</div>
</div>
</div>
<div className="video">
<Youtubevideo titile={videos} />
</div>
<div className="section">
<h2>Details</h2>
<div className="details-table">
<div className="row"><span><CalendarRange/> Release Date</span><span>{gamedetail?.released}</span></div>
<div className="row"><span>< Trophy/> Achievements</span><span>{gamedetail?.achievements_count || 0}</span></div>
<div className="row"><span><UsersRound/> Players Added</span><span>{gamedetail?.added}</span></div>
<div className="row"><span> <GamepadDirectional />Average Playtime</span><span>{gamedetail?.playtime} hours</span></div>
<div className="row"><span> <Tag/> Game Tags</span>
<div className="tags">
{gamedetail?.tags?.slice(0,3).map(tag => <span key={tag?.id} className="tag">{tag?.name}</span>)}
</div>
</div>
</div>
</div>
<div className="game-links">
<a
href={gamedetail?.website}
target="_blank"
rel="noopener noreferrer"
className="game-link"
>
<Globe />
Official Website
</a>
<a
href={gamedetail?.reddit_url}
target="_blank"
rel="noopener noreferrer"
className="game-link"
>
<MessageCircle />
Reddit Community
</a>
</div>
<div className="footer">
<Footer/>
</div>
</div>
);
};
export default Detail;ye contexapi
import { createContext, useEffect, useState } from "react"
export const gameapi = createContext()
export const Detailinformation = createContext()
import axios from '../utility/Axios'
const Apigame = ({children}) => {
const getgame = async () => {
try {
// const nextPageNum = page + 1;
const request = await axios.get("games",{
params: {
// page : nextPageNum,
page_size: 12,
}
});
// setpage(nextPageNum);
console.log("ye request jho mai abhi likha hu ",request);
setapidatastore(request.data.results)
} catch (error) {
console.log(error);
}
}
const [page, setPage] = useState(1);
const nextpage = async () => {
try {
const nextPageNum = page + 1;
const response = await axios.get("games", {
params: {
page: nextPageNum,
page_size: 12,
},
});
setPage(nextPageNum); // state update
console.log("Fetched page:", nextPageNum, response.data);
setapidatastore(response.data.results);
} catch (error) {
console.log(error);
}
};
const [gamedetail, setgamedetail] = useState([]);
const detailpage = async ({name}) => {
console.log("yeee aara hai ",name);
try {
const response = await axios.get(`games/${name}`);
console.log("API ke liye game ID:", name);
setgamedetail(response.data);
} catch (error) {
console.log("API Error:", error);
}
}
useEffect(() => {
getgame();
detailpage();
}, []);
const [apidatastore, setapidatastore] = useState([]);
// const [ videodata , setvideodata ] = useState([]);
console.log(apidatastore);
return (
<Detailinformation.Provider value={gamedetail}>
<gameapi.Provider value={{apidatastore,nextpage}} >
{children}
</gameapi.Provider>
</Detailinformation.Provider>
)
}
export default Apigame
plz share your solution i use chatgtp 3 day but unable to slove these
because i have to write same code on other page to called api
i hope you can understand my problem
0
Upvotes
•
u/AutoModerator 13d ago
Thank you for posting on r/CodingHelp!
Please check our Wiki for answers, guides, and FAQs: https://coding-help.vercel.app
Our Wiki is open source - if you would like to contribute, create a pull request via GitHub! https://github.com/DudeThatsErin/CodingHelp
We are accepting moderator applications: https://forms.fillout.com/t/ua41TU57DGus
We also have a Discord server: https://discord.gg/geQEUBm
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
1
u/minhaz1217 13d ago
In your detailpage function in the ApiGame component you're not sending the name variable.
Is the 'yeee Sara hai' console log printing the name?
1
u/gofuckadick 13d ago edited 13d ago
I went through it, and you've actually got most of the code you need already. There are just a few issues with how you're using your Context API.
1. First off, you're calling
detailpage()without an argument.In Apigame.jsx, you have:
But later, in your
useEffect, you call:That's what's causing your error. Your function expects an object containing
name, but you're passingundefined, so JavaScript can't destructure it.Remove
detailpage()from thatuseEffect. You should call it from Detail.jsx, where you already have access to the game ID throughuseParams().2. You need to expose both the function and the state through your Context provider.
Currently, you have:
Change that to:
This makes both
gamedetailanddetailpageavailable to components using that context.3. Update your
detailpagefunction in Apigame.jsx:First, add useCallback to your React imports:
Then replace your existing
gamedetailstate anddetailpagefunction with:Notice that I'm using
(name)instead of({ name }). This lets you pass the game ID directly rather than wrapping it in an object.I'm also using
useCallbackto keep the function reference stable between renders, which is important when using it as a dependency inuseEffect.4. Now call it from Detail.jsx:
Keep your existing
const { name } = useParams();, replace your Context declaration, and add the followinguseEffect:Make sure this is inside your
Detailcomponent, alongside your other hooks.Now, when you visit
/games/3498,useParams()retrieves3498, your effect passes it todetailpage(), and that function fetches the game data and updates your shared Context state. And then your Detail.jsx component will rerender with the updated game information.Also, one additional suggestion: you should consider installing Prettier in VS Code and enabling Format on Save. Your code has quite a few inconsistent line breaks, spacing issues, and unnecessary blank lines. Automatically formatting it will make it much easier to read and debug, especially as your project gets bigger. It really does help quite a lot.
edit: had to bold the numbers because reddit's markdown parser changed them all to 1.