It is my first time js and react.js project. and I have a problem with printing out json array data.
Here's my code
const [appData, setAppData] = useState({});
const [appdevData, setAppdevData] = useState('');
axios
.all([
.get(url1)
.get(url2)
])
.then(
axios.spread((res1, res2) => {
const data1 = res1.data;
const data2 = res2.data;
setAppData(data1);
setAppdevData(data2().results[0].developer.name);
})
}, []);
return (
<section className={styles.itemDisplaySection}>
<div className={styles.itemDisplayFlex}>
<table className={styles.itemDisplayTable}>
<tr>
<td>APP ID</td>
<td>{appData.app_id}</td>
</tr>
<tr>
<td>APP Type</td>
<td>{appData.type}</td>
</tr>
<tr>
<td>Developer</td>
<td>{appdevData.results[0].developer.name}</td>
</tr>
<tr>
<td>Release Date</td>
<td>{appData.release_date}</td>
</tr>
</table>
</div>
</section>
);
and here is my appData.json, and appdevData.json data.
appdata.json
{
"app_id": 1089090,
"name": "testdata",
"header_url": "https://cdn.akamai.steamstatic.com/steam/apps/1089090/header_koreana.jpg?t=1658473684",
"release_date": "2020-03-26",
"type": "game",
"basegame_id": null
}
appdevData.json
{
"count": 1,
"next": null,
"previous": null,
"results": [
{
"app_dev_id": 76,
"app": "Django-server-url",
"developer": {
"developer_id": 65,
"name": "SMILE"
}
}
]
}
but still there is print issue with results[] array. here is my error code.
// with appdevData.results[0].developer.name
Cannot read properties of undefined (reading '0')
I've been trying to fix with map func, and props components and still have problem with it.
I know it's a simple array print out issue, but I can't find a way to fix this error.
plz help me.
CodePudding user response:
When setting your appdevData
change the code to (data2
is not a function):
axios.spread((res1, res2) => {
const data1 = res1.data;
const data2 = res2.data;
setAppData(data1);
if (!data2.results || data2.results.length == 0) return;
setAppdevData(data2.results[0].developer.name);
})
Also, you could set your default appData
state to null and add conditional rendering to prevent errors due to accessing properties during load.
Finally, you should display the appdevData
state instead of appdevData.results[0].developer.name
:
const [appData, setAppData] = useState(null);
const [appdevData, setAppdevData] = useState('');
...
if (!appData) return <>Loading data...</>
return (
<section className={styles.itemDisplaySection}>
<div className={styles.itemDisplayFlex}>
<table className={styles.itemDisplayTable}>
<tr>
<td>APP ID</td>
<td>{appData.app_id}</td>
</tr>
<tr>
<td>APP Type</td>
<td>{appData.type}</td>
</tr>
<tr>
<td>Developer</td>
<td>{appdevData}</td>
</tr>
<tr>
<td>Release Date</td>
<td>{appData.release_date}</td>
</tr>
</table>
</div>
</section>
);