Introduction
here we are again with the simplest useState example where when ever the state is changed we are calling an API storing the details to a different state and displaying it
import React, { useState, useEffect } from 'react'
import { ClipboardCheck } from 'react-bootstrap-icons'
//whenever we wants to mounts a component or unmount based on any change to the state
// we will be using the useState component.
const First = () => {
const [resourceType, setResourceType] = useState('posts')
const [message, setMessage] = useState([])
const fetchData = () => {
fetch(`https://jsonplaceholder.typicode.com/${resourceType}`)
.then((response) => response.json())
.then((json) => {
setMessage(json)
})
}
useEffect(() => {
fetchData()
}, [resourceType])
return (
<div>
<button onClick={() => setResourceType('posts')}>Posts</button>
<button onClick={() => setResourceType('users')}>Users</button>
<button onClick={() => setResourceType('comments')}>Comments</button>
<div>
<h2>
{message.map((item) => (
<h6>{JSON.stringify(item)}</h6>
))}
</h2>
</div>
</div>
)
}
export default First