CodexBloom - Programming Q&A Platform

Handling Nested JSON Objects in React with Axios – how to to Access Deeply Nested Properties

πŸ‘€ Views: 53 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-28
react axios json JavaScript

I'm maintaining legacy code that I'm working on a React application where I'm trying to fetch data using Axios from an API that returns a complex JSON structure. The JSON response looks like this: ```json { "user": { "id": 123, "name": "John Doe", "posts": [ { "title": "First Post", "comments": [ { "id": 1, "content": "Great post!" }, { "id": 2, "content": "Thanks for sharing!" } ] } ] } } ``` I successfully fetch the data like this: ```javascript import React, { useEffect, useState } from 'react'; import axios from 'axios'; const App = () => { const [userData, setUserData] = useState(null); useEffect(() => { axios.get('https://api.example.com/user/123') .then(response => setUserData(response.data)) .catch(behavior => console.behavior('behavior fetching data:', behavior)); }, []); return ( <div> {userData ? <h1>{userData.user.name}</h1> : <p>Loading...</p>} </div> ); }; export default App; ``` However, I am struggling to access the nested properties of the user’s posts and comments. When I try to render the titles of the posts along with their comments, I’m not sure how to navigate through the nested structure. For instance, I want to display the post titles and each comment under them like this: ``` First Post - Great post! - Thanks for sharing! ``` I attempted the following code, but it seems to be returning `undefined` for the posts and comments: ```javascript {userData && userData.user.posts.map(post => ( <div key={post.title}> <h2>{post.title}</h2> <ul> {post.comments.map(comment => ( <li key={comment.id}>{comment.content}</li> ))} </ul> </div> ))} ``` The behavior I’m getting in the console is `TypeError: want to read properties of undefined (reading 'map')`. It seems like `userData.user.posts` might not be defined at the time of rendering. I’ve tried adding conditional checks, but they don't seem to resolve the scenario. What’s the best way to handle this situation and ensure I'm accessing the deeply nested properties correctly? Any advice would be greatly appreciated! I'm on Windows 10 using the latest version of Javascript. I'd really appreciate any guidance on this.