reactfetchingdata
1:--using fetch
import React,{useState,useEffect} from 'react'
export default function Fetch() {
const [post,setPost]=useState([]);
useEffect(()=>{
fetch(`https://jsonplaceholder.typicode.com/posts`)
.then((response) => {
response.json().then(data=>{
console.log(data);
setPost(data);
}
)
})
.catch((error) => {
console.log(error);
// Code for handling the error
});
},[])
return (
<div>
<select>
{post.slice(0,15).map((e,index)=><option id={index}>{e.id}</option>)}
</select>
{/* <select> */}
{/* {post.slice(0,15).map(e=>{e.id})} */}
{/* </select> */}
</div>
)
}
using axios:--
import React,{useState,useEffect} from 'react'
import axios from 'axios';
export default function Fetch1() {
const [post,setpost]=useState([]);
const getData=()=>{
axios.get('https://jsonplaceholder.typicode.com/posts')
.then((response) => {
console.log(response.data);
setpost(response.data)
})
.catch((error) => {
console.log(error);
})
}
useEffect(getData(),[])
return (
<div>
<select>
{post.slice(0,15).map((e,index)=><option
id={index}>{e.id}</option>)}
</select>
</div>
)
}
3:
import axios from 'axios';
import React,{useState,useEffect} from 'react'
import './style/table.css';
export default function DataFech1() {
const [data,setData]=useState([]);
useEffect(async()=>{
try{
const res=await axios.get(`https://jsonplaceholder.typicode.com/posts`);
console.log(res);
setData(res.data);
}
catch(error){
console.log(error);
}
},[])
return (
<>
<table ><thead><tr><th>Id</th><th>Title</th></tr></thead>
{data.map((e,index)=>(
<tbody>
<tr> <td key={index}>{e.id}</td><td>{e.title}</td></tr>
</tbody>
))}
</table>
</>
)
}
{post.slice(0,15).map((e,index)=><li key={index}>
{e.id}{e.title}
Comments
Post a Comment