I am working on Reactjs and i am using nextjs, Right now i am using axios for fetch data via api but unable to display in page,For this i am trying to console.log inside "useEffect" but nothing is displaying, How can i use console.log and display data in my page? Here is my current code
import dynamic from 'next/dynamic';
import React, { FormEventHandler, useRef } from 'react';
import { Editor } from '@tinymce/tinymce-react';
import { useEffect, useState } from "react";
import axios from 'axios';
import $ from 'jquery';
const Test=()=>{
const[post,setPosts]=useState([]);
useEffect(() => {
const getPosts = async () => {
const { data: res } = await axios.get(
"https://diggdevelopment.com/blackstallion_new/api/get_demodata/"
)
console.log('here is data'+ res);
setPosts(res);
};
getPosts();
}, []);
return(
<>
<table className="table">
<thead>
<tr>
<th>Id</th>
<th>Title</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{post.length > 0 ? (
post.map((post: any, index: number) => (
<tr key={post.id}>
<td>{post.id}</td>
<td>{post.title}</td>
</tr>
))
) : (
<></>
)}
</tbody>
</table>
</>
);
}
export default Test;
You should use try-catch block
You can try this code below:
useEffect(() => {
const getPosts = async () => {
try {
const res = await axios.get(
"https://diggdevelopment.com/blackstallion_new/api/get_demodata/"
);
console.log("here is data", res);
setPosts(res.data.blogs);
} catch (err) {
console.log(`ERROR: ${err}`);
}
};
getPosts();
}, []);
Live demo here: https://codesandbox.io/s/intelligent-rgb-m0zglq?file=/src/App.js:304-594
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.