Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

94
Views
useState solo funciona en el segundo clic al actualizar la información actual en un enlace API a través de Hooks y useEffect

Estoy aprendiendo React y me he enfrentado al siguiente problema con useState: cuando se hace clic en el botón, los datos se establecen en nulo (que es el estado inicial en el enlace) después del primer clic, pero luego en el segundo clic obtengo el resultado Quiero (quiero incrementar solo el valor de las estrellas al hacer clic). Entiendo que, dado que useState y setState son solo colas, solo se actualizan de manera asíncrona. Intenté usar useEffect para mitigar esto, pero el programa termina renderizándose antes de hacer clic en el botón. Aquí está mi código:

 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') } }) }

Aquí es donde llamo a 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;
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!