Home > front end >  Rendering nested json response data in react UI
Rendering nested json response data in react UI

Time:10-25

This is the structure of the json being fetched. I am trying to render some of the nested threads data to a web page with react.

enter image description here

import react, {useState, useEffect} from "react";
import axios from 'axios'
import ReactJson from 'react-json-view'

const FeaturedBoards = () => {
    const [boards, setBoards] = useState([{page: '', threads: {}}]); 

useEffect(() => {
    fetchBoards();
}, []);

const fetchBoards = () => {
    axios.get('https://a.4cdn.org/po/catalog.json')
    .then((res) => {
        console.log(res.data);
        setBoards(res.data);
    })
    .catch((err) => {
        console.log(err);
    });
};
    if(boards === 0) {
        return <div>Loading...</div>;
    }
    else{
    return (
        <div>
            <h1>Featured Boards</h1>
            <div className='item-container'>
                {boards.map((board) => (
                    <div className='board' key={board.id}>
                        <p>{board['threads']}</p>
                    </div>
                ))}
            </div>
        </div>
    );
    }
};

export default FeaturedBoards;

I have tried everything to display some of the nested threads data but nothing comes up. I've tried doing a second call to map on board but no luck, storing it in a variable and calling from that still nothing. Am I doing something totally wrong?

enter image description here

CodePudding user response:

I believe this is more fully answered by How can I access and process nested objects, arrays or JSON?. but to explain for this particular data structure, keep reading.


Look at your actual data... boards is an array. Each element in it is an object with page (int) and threads (array) properties. Each threads array element is an object with other properties. You can use map to iterate arrays and return a JSX representation of the objects within.

For example

const [boards, setBoards] = useState([]); // start with an empty array
const [loading, setLoading] = useState(true)

useEffect(() => {
  fetchBoards().then(() => setLoading(false))
}, []);

const fetchBoards = async () => {
  const { data } = await axios.get('https://a.4cdn.org/po/catalog.json')
  setBoards(data)
}

return loading ? <div>Loading...</div> : (
  <div>
    <h1>Featured Boards</h1>
    <div className="item-container">
      {boards.map(board => (
        <div className="board" key={board.page}> <!--            
  • Related