简体   繁体   中英

I am unable to access Json data and display it in table using axios in React

I am trying to access json data using hooks and display it in the

tag but it is showing error-"TypeError: states.map is not a function".I also used Array.from() to convert my json to array and it did not showed any error but also did not display anything.

  var rows=[{}];
  export default function Mainpage() {
const [states, setstate] = useState([]);
const getLatestJSPost = () => {
    const API_URL = "http://localhost:8080/Displaydo";
    axios
    .get(API_URL)
    .then((response) => {
        
        // rows = Array.from(response.data);

        console.log(response.data);
        setstate(response.data)

    })
    };
    useEffect(() => {
        getLatestJSPost();        
        
    }, [])
return (
    <div>
        <p>Hello</p>
        { states.map((ndata) => { 
                return <p key={ndata.doc_id}> {ndata.doc_id} </p>
                })}  
    </div>
)

}

The conole.log(response.data) looks like Output of console.log(response.data)

you can do it this way:

 <div>
    <p>Hello</p>
    {states.length>0 && states.map((ndata) => { 
            return <p key={ndata.doc_id}> {ndata.doc_id} </p>
            })}  
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM