No puedo averiguar cómo acceder a este objeto Promise. ¿Cómo mapear esta promesa? ¿Y por qué mi función async/await devuelve una promesa y no un objeto de resultado? Cualquier comentario apreciado.
Promise {<pending>} [[Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: Array(2) 0: "hey" 1: "bye" length: 2[[Prototype]]: Array(0) import { io } from "socket.io-client"; import { useState, useEffect } from "react"; function App() { const [text, setText] = useState(""); const [socket, setSocket] = useState(); const [chat, setChat] = useState([]); useEffect(() => {...}, []); ***//getting previous chat for new users.*** useEffect(async () => { let mounted = true; const response = await fetch("http://localhost:4000/main_chat").then( (res) => { if (mounted) { setChat(res.json()); } } ); return () => (mounted = false); }, []); useEffect(() => {...},[socket]); const handleClick = () => { socket.emit("sentFromClient", text); }; return ( <div> <ul>{console.log(chat)}</ul> <input value={text} onChange={(e) => setText(e.target.value)}></input> <button onClick={() => handleClick()}>enter</button> </div> ); } export default App;fetch devuelve una Promesa, que espera, pero luego res.json() devuelve otra Promesa, que no espera. De modo que Promise se pasa a setChat y se convierte en el valor de chat .
También está mezclando await y .then , que hacen lo mismo, por lo que probablemente solo deba usar uno u otro.
Con await :
const response = await fetch(...) const json = await response.json() setChat(json) Con .then :
fetch(...) .then(response => { return response.json() }) .then(json => { setChat(json) }) Finalmente, tiene razón al verificar si todavía está montado antes de llamar a setChat , pero pasar una función asíncrona a useEffect no funcionará porque necesita devolver la función de limpieza ( () => (mounted = false) ), y las funciones asíncronas devuelven promesas. Asi que:
useEffect(() => { let mounted = true const getChat = async () => { await whatever... if (mounted) setChat(something) } getChat() return () => (mounted = false) })O
useEffect(() => { let mounted = true fetch(...).then(chat => { if (mounted) setChat(chat) }) return () => (mounted = false) })Está utilizando tanto .then() como async\await await, lo cual es un poco confuso. Tal vez debería comenzar eliminando console.log() de la expresión JSX devuelta. Luego, dentro de su gancho useEffect, actualícelo a este
useEffect(async () => { let mounted = true; const response = await fetch("http://localhost:4000/main_chat") if (mounted) { // consol.log(response) here should give you the value returned by the API setChat(response); } // Not sure why are you returning this function definition return () => (mounted = false); }, []);