'useState only functions on second click when updating the current information in an API link through Hooks and useEffect
I am learning React and I have been facing the following issue with useState: when the button is clicked the data is set to null (which is the initial state in the hook) after the first click but then on the second click I get the result I want (I want to increment only the value of stars on click). I understand that since useState and setState are just queues, they only update in an asynchronous manner. I have tried using useEffect to mitigate this but the program ends up rendering before the button is clicked. Here is my code :
const UniversityDetails = () => {
const { id } = useParams();
const {data,isPending} = useFetch("http://localhost:8000/universities/" + id);
const [stars,setStars] = useState(null);
const [name,setName] = useState(null);
const [Location,setLocation] = useState(null);
const [students,setStudents] = useState(null);
const [foundation,setFoundation] = useState(null);
const handleClick = () => {
const things = {stars, name, Location, students, foundation};
fetch("http://localhost:8000/universities/4", {
method: "PUT",
headers: {"Content-Type": "application/json"},
body: JSON.stringify(things)
}).then(() => {
data &&
setStars(data.stars + 1)
setName(data.name)
setLocation(data.Location)
setStudents(data.students)
setFoundation(data.foundation)
}).catch(err => {
if (err.name === 'AbortError') {
console.log('fetch aborted')
}
})
}
Here is where I call handlclick:
return (
<div className="UniversityDetails">
{isPending && <h2>Loading...</h2>}
{data &&
<article >
<h1> {data.name}</h1>
<h3> Total stars: {data.stars}</h3>
<h3> Number of students: {data.students}</h3>
<h3>Year of foundation: {data.foundation}</h3>
</article>}
{data && <button onClick={handleClick}>
<h4 style={{color:"white",fontWeight: "bold",fontSize:17}}>UPVOTE !</h4>
<h4 style={{fontSize:13,marginTop:1,color:"white",fontWeight: "lighter"}}>Total stars: {data.stars}</h4>
</button> }
</div>
);
};
export default UniversityDetails;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
