Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138192

React-Router not receiving props if it's the same path, but different param?

$
0
0

I have a path /player/:id/

If I navigate from say /player/12 to /player/13 it will error out, for example: cannot find foo of undefined. However if I navigate from a different path such as /heroes/100 to /player/12 it will load fine.

My suspicion is that when I link from the same route, but different param, the new page is not invoking my useEffect or setState hooks.

I feel like I'm missing something fundamental here, but I can't figure it out. If my suspicion is correct, does anyone know how i can force my component to use my UseEffect and UseState hooks before loading the page when going from the same route, but different params?

The params are correct, it's displaying the correct id in the url bar. If i refresh the page it'll load fine, but if i click the link it'll error out Cannot read property 'hero_id' of undefined

Thank you

Context:

playedAgainst.map(player => <Link key={Math.random()} to=
{"/players/" + props.invertedPlayers[player]}> <span> {player} </span></Link>

Each iteration creates a new Player name, with a Link. When i click on that link it says all "cannot read property hero_id of undefined". However, when i refresh the page it loads fine. I'm 100% sure the link path is correct. I used the exact same code in a different component that leads to the Player component.

(The Math.random is definitely sloppy, i'll remove that!)

<Header />
        <Switch>
          <Route exact path="/">
            <Search players={this.state.players} />
            <GameList players={this.state.players} data={this.state.games} />
            <Footer />
          </Route>
          <Route exact path="/players/:id">
            <Player players={this.state.players} invertedPlayers = {_.invert(this.state.players)} />
          </Route>
          <Route exact path="/heroes/:id">
            <Heroes players={this.state.players} invertedPlayers = {_.invert(this.state.players)} />
          </Route>
        </Switch>
        </Router>

EDIT -

I added the following hook to my Players component.

  useEffect(() => {
    console.log('useEffect fired');
}, [])

When i go from 1 id to another (same route, different param) the useEffect hook is not firing.

Seems like i need to get my useEffect to fire when following the same routes with different ids.

Accessing my Params via useParams():

let { id } = useParams();
  const [player, setPlayerData] = useState({ data: null, image: null });
  useEffect(() => {
    const fetchData = async () => {
      const response1 = await axios(`/api/players/${id}`);
      const response2 = await axios(`/api/saveImage/${id}`)
      setPlayerData({ data: response1.data, image: response2.data });
    };
    fetchData();
  }, []);

EDIT 2 -

Added to ID to useEffect, but useEffect is still not rerunning for some reason:

let { id } = useParams();
  const [player, setPlayerData] = useState({ data: null, image: null });
  useEffect(() => {
    const fetchData = async () => {
      const response1 = await axios(`/api/players/${id}`);
      const response2 = await axios(`/api/saveImage/${id}`)
      setPlayerData({ data: response1.data, image: response2.data });
    };
    fetchData();
  }, [id]);

EDIT 3 -

More context, hopefully this helps:

As soon as the component loads it pulls data from the API to load within the component. This works fine. When i click a ling to the same route, but different param, the useEffect hook to pull data doesn't run.

const Player = (props) => {
  let { id } = useParams();
  const [player, setPlayerData] = useState({ data: null, image: null });
  useEffect(() => {
    const fetchData = async () => {
      const response1 = await axios(`/api/players/${id}`);
      const response2 = await axios(`/api/saveImage/${id}`)
      setPlayerData({ data: response1.data, image: response2.data });
    };
    fetchData();
  }, [id]);

  useEffect(() => {
    console.log('count changed');
}, [])

  console.log('test')
    return (
        <div className="historyContainer">
...............

{player.data && player.data.map((game, i) => {
    const heroIdOfPlayer = game.players.find(p => p.account_id === +id).hero_id; 
    const teamOfPro = game.players.find(p => p.hero_id === +heroIdOfPlayer).team;

The part under the '.......' is where Cannot read property 'hero_id' of undefined is coming from, which only happens when clicking through the link.

A few lines further down:

{playedAgainst ?
            playedAgainst.map(player => <Link key={Math.random()} to={"/players/" + props.invertedPlayers[player]}><span> {player} </span></Link>)
            : ""}

This is how each link is generated. The path is correct. if i follow the path it'll say Cannot read property 'hero_id' of undefined, but when i refresh the page it will load fine.


Viewing all articles
Browse latest Browse all 138192

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>