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;