26
loading...
This website collects cookies to deliver better user experience
import React,{useState,useEffect} from 'react'
/*here we have imported the useState to change the state of the
data when the data gets update on the end point and useEffect
is used to fetch the data from the api
and it will run on every render
*/
const [todos, setTodos] = useState([]);
//useState is set to an empty arraya and later
//we will fetch the data from the end point
//and will store in the 'todos' array
useEffect(() => {
fetch('http://jsonplaceholder.typicode.com/todos')
.then(res => res.json())
.then((data) => {
setTodos(data)
console.log(todos)
})
}, [todos]);
{todos.map((todo) => (
<div className="card bg-dark text-light my-3">
<div className="card-body">
<h5 className="card-title">{todo.title}</h5>
<h6 className="card-subtitle mb-2 text-muted">
{ todo.completed &&
<span>
Completed
</span>
}
{ !todo.completed &&
<span>
Pending
</span>
}
</h6>
</div>
</div>
))}
import React,{useState,useEffect} from 'react'
import Fade from 'react-reveal/Fade'
import {Navbar,NavbarBrand,NavbarToggler,Nav,NavItem,NavLink,Collapse} from 'reactstrap';
import './App.css'
function App() {
const[toggle,setToggle] = useState(false);
const isToggle = () => setToggle(!toggle);
const [todos, setTodos] = useState([])
useEffect(() => {
fetch('http://jsonplaceholder.typicode.com/todos')
.then(res => res.json())
.then((data) => {
setTodos(data)
console.log(todos)
})
.catch(console.log)
}, [todos])
return (
<div className="">
<h1 className="text-primary text-center display-4 mb-5">React fetch api using useEffect</h1>
<div className="text-center" style={{display:"block",width:"50%",margin:"0 auto"}}>
<div style={{display:"flex",flexDirection:"column",justifyContent:"center",justifyItems:"center",width:"100%"}}>
{todos.map((todo) => (
<div className="card bg-dark text-light my-3">
<div className="card-body">
<h5 className="card-title">{todo.title}</h5>
<h6 className="card-subtitle mb-2 text-muted">
{ todo.completed &&
<span>
Completed
</span>
}
{ !todo.completed &&
<span>
Pending
</span>
}
</h6>
</div>
</div>
))}
</div>
</div>
</div>
)
}
export default App