I want to get values from the Map and for each of them make a tag, but when I’m trying to do .get function on Map passed from App.js it shows:
Uncaught TypeError: playerData.get is not a function
at PlayerStats (PlayerStats.jsx:16:1)
at renderWithHooks (react-dom.development.js:14985:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22776:1)
at workLoopSync (react-dom.development.js:22707:1)
Here is my file where is the problem:
const PlayerStats = ({ playerData }) => {
console.log(playerData);
console.log(playerData.get("0"));
return (
<main>
<div/>
<Grid container justify="center" spacing={4}>
</Grid>
</main>
)
and the App.js:
const App = () => {
const [ playerData, setPlayerData ] = useState([]);
const handlePlayerData = () => {
var http = new XMLHttpRequest();
http.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
var result = JSON.parse(this.responseText);
let index = 0;
var playerDatas = new Map();
result.data.forEach(function(element) {
var dane = JSON.parse(element.Data);
var mapa = new Map();
mapa.set("isOnline", dane.isOnline);
mapa.set("Name", element.Name);
playerDatas.set(index, mapa);
index++;
})
setPlayerData(playerDatas);
}
}
http.open("GET", "https://example.com/", true);
http.send();
}
useEffect(() => {
handlePlayerData();
}, []);
return (
<div>
<PlayerStats playerData={playerData} />
</div>
);
}
Though, when console.log(playerData); it normally shows a map on console. I’ve check that the requested value is on the map.
>Solution :
You are initializing playerData as an array at the beginning.
const [ playerData, setPlayerData ] = useState([]);
Can you try changing the above line as
const [ playerData, setPlayerData ] = useState(new Map());