So I'm super new to react. I have some code where I use fetch to get data from an API (that I created, structured like {'userData': {'overall': {'rank': '10', 'level': '99', 'xp': '200000000'}}}) and I display it on screen. It was working fine for hours and now all of a sudden without touching any code, it's broken. it will display the data just fine if i make an API request and then refresh the page. but then when I refresh the page again it tells me "Uncaught TypeError: Cannot read properties of undefined (reading 'overall')" I don't know what I'm doing wrong and I'm wondering if someone can help me because I don't know how it became undefined, it was reading it just fine and then on refresh it changes to undefined. here's my code for the component
function Activities() {
let name = "three-dawg";
function fetchPlayerData(name){
fetch(URL)
.then(response => response.json())
.then(data => setPlayerData(data));
};
function refreshPage() {
window.location.reload(false)
}
const [playerData, setPlayerData] = useState([]);
useEffect(() => {fetchPlayerData(name)}, [name]);
return (
<div>
Hello {playerData._id}
<button onClick={() => {
fetchPlayerData(name)
refreshPage()
}}>load player</button>
<ul>
<li>{playerData.userData.overall.rank}</li>
</ul>
</div>
);
}
window.location.reload(false)in a React app. And you're not changing thenamevariable anywhere so thatuseEffectis redundant. You may wantuseEffect(() => ... [])with an empty dependency array instead. FYI code rarely stops working. What did you change?