i have this code that is giving me Uncaught (in promise) TypeError: pr is undefined
when i change
const pr = getINFOPlayerRank.find(rank => name.id === rank.id)
to
const pr = getINFOPlayerRank.find(name => name.id === name.id)
i get a response and table shows but the second api only displays the first line of data over and over:
MY CODE
import axios from "axios";
import React, { useState, useEffect } from "react";
const News = () => {
const [playerName, setPlayerName] = useState([]);
const [playerRank, setPlayerRank] = useState([]);
const [player, setPlayer] = useState([]);
const fetchData = () => {
const playerAPI = 'http://localhost:3008/api/players';
const playerRank = 'http://localhost:3008/api/highscore/players';
const getINFOPlayer = axios.get(playerAPI)
const getPlayerRank = axios.get(playerRank)
axios.all([getINFOPlayer, getPlayerRank]).then(
axios.spread((...allData) => {
const allDataPlayer = allData[0].data.players
const getINFOPlayerRank = allData[1].data.players
const newPlayer = allDataPlayer.map(name => {
const pr = getINFOPlayerRank.find(rank => name.id === rank.id)
return {
id: name.id,
name: name.name,
status: name.status,
position: pr.position,
score: pr.score
}
// or simply do the following if the keys doesn't matter: return {...name, ...pr}
})
setPlayerName(allDataPlayer)
setPlayerRank(getINFOPlayerRank)
console.log(newPlayer)
setPlayer(newPlayer)
})
)
}
useEffect(() => {
fetchData()
}, [])
return (
<table >
<tr>
<th>Rank</th>
<th>Name</th>
<th>Points</th>
</tr>
<tbody>
{player?.map((name) => {
return (
<tr key={name}>
<td>{name.name}</td>
<td>{name.id}</td>
<td>{name.status}</td>
<td>{name.position}</td>
<td>{name.score}</td>
</tr>
)
})}
</tbody>
</table>
)
}
export default News
CodePudding user response:
Try using optional chanining:
return {
id: name.id,
name: name.name,
status: name.status,
position: pr?.position,
score: pr?.score
}