1
import React,{useState, useEffect} from 'react'
import { useParams } from 'react-router-dom'
import Home from './Home'
import './detailpage.css'
function DetailPage({name,
  info,
  genre,
  _id,
  episodeNumber,
  poster}) {
  const [shows, setShows]= useState([{name:'',
  info:'',
 airingDate:'',
 _id:'',
 genre:'',
 episodeNumber:'',
  poster:''
 }])

const params= useParams();

useEffect(()=>{  
fetch("/home")
.then(res => res.json())          
.then(jsonRes => setShows(jsonRes))
 
}, [])

const b = JSON.stringify(params);

const newShows = shows.filter(a=>a._id===b) 

console.log(newShows)


return (
    <div>
<h2>.</h2>
<h2>.</h2>
<h2>.</h2>
  <h2>{JSON.stringify(params)}</h2>
 <h2>{shows.genre}</h2>
{newShows.map(a=>
  <div>
<div className='container'>
    <img className='showImg' src={a.poster} alt=''></img>
    <h2 className='showTitle'>{a.title}</h2>
    <h3>{a.genre}</h3>
    <p className='showInfo'>{a.info} </p>
    </div>

    </div>
  
  )}
<h2>{episodeNumber}</h2>
<h2>{shows.info}</h2>
    </div>
  )
}

export default DetailPage

I have tv shows on my Home page and after clicking the image I want it to load the detail page about the clicked show however I couldn't manage to do it. I tried 'filter' method in the code but it didn't work I also tried like this

const newShows = shows.filter(a=>a.genre.length>5) 

it works but this is not what I want. I would be really happy if someone could've helped. Thank you so much.

1 Answer 1

1

If I were you, I wouldn't use this fetch, as when you click on the image from your home you already know which tv show you want to display more details about.

I would use something like useLocation from react-router-dom, and while changing pages (home -> detail page about a tv show) carry a state variable with the specific tv show details.

https://v5.reactrouter.com/web/api/Hooks/usehistory

const handleClick = (state) => {
    history.push({ pathname: "/detail-page", state })
}

<YourTvShowImage onClick={() => handleClick(TvShowData)} />

Then on your detail page class you use something like

https://v5.reactrouter.com/web/api/Hooks/uselocation

  const location = useLocation()
  const [tvShowData, setTvShowData] = useState()
  
  useEffect(() => {
    if (location.state) {
      setTvShowData(location.state)
    }
  }, [location])
Sign up to request clarification or add additional context in comments.

1 Comment

I can't use history because of react-router-dom V6 and using navigate instead of it , when I try to write tvshowdata in handleclick I'm getting undefined error. Should I define it at home page too? And yeah it's much more reasonable then fetching it all again. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.