Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

122
Vistas
Trouble with Promise in React

Im a beginner at React and I was recently going across this Asynchronous Data fetching and tried to simulate it by using Promise in the following code.(Data fetching takes time so yes I should use setTimeout() with Promise but code here is for simplicity)

function List({stories})
{
    console.log("Hi from List");                 //Testing if component is rendered 
    return(<>
        {
           stories.map(function(element)
           {
               return (<li>{element.title}</li>);
           })
        }
        </>);
}

function App()
{
    const stories=[
        {title:"Alice in Wonderland"},
        {title:"Beauty & the Beast"}
    ];

    const [newStories,setNewStories]=React.useState([]);
    
    function wait()
    {
        console.log("Check");                           //To see if code works here
        Promise.resolve({data:stories});
    }
    
    React.useEffect(function()
                {
                   wait().then(result=>setNewStories(result.data))
                },[]);

    return(
        <>
        <h1>{"Titles"}</h1>
        <hr/>
        <List stories={newStories}/>
        <hr/>
        </>
    );
}

The above code produces the desired output(only for half a second or so) and then immediately proceeds to give a white blank screen but when I replace the following it works perfectly.

React.useEffect(function()
                {
                Promise.resolve({data:stories}).then(result=>setNewStories(result.data))
            },[]);

My question is why is it not working when Promise is inside a function and why do I get this "Uncaught Type Error" for wait() ?

(The code does print "Check" in the console,So why is it all of a sudden claiming the function to be undefined??)

EDIT I apparently have to put a return statement there

Thanks @Andy and others

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

🎨 JavaScript Style

First, let me first show you a style guide to writing better JavaScript: https://github.com/airbnb/javascript

Writing good JavaScript code is essential so that your code is readable, not just by you but by everybody on StackOverflow and the individuals you are working with.

  • Curly braces should not be on its own new line
  • Spaces should be used instead of tabulation characters
  • Indent things correctly (using either 2 or 4 spaces)
  • JSX should have an indented structure
  • Don't indent randomly and whenever you feel like it, only when expected, and always when expected
  • End-of-line comments should appear only 1 space away from the code

👷‍♀️ Promises

Promises are meant for asynchronous resolution, ex: if you are waiting for an event, such as a network request to come back with a response. This is because when creating a network request, a new thread is spun up so the rest of your JavaScript code can run instead of waiting for the response.

Promises should not be used when simply returning a value.

// ✅ Good code
function wait() {
    return something
}

// 💩 Bad code
function wait() {
    // (This is the correct way to write a Promise resolution)
    return new Promise(resolve => resolve(something));
}

Additionally, if you would like to write an asynchronous function that returns a promise, but you are not actually creating new threads, you want to use async/await:

async function wait() {
    return something;
}

✅ Your Solution

The answer to your solution is simple. Your wait function does not return anything. Just creating a promise will not do anything, you have to return it.

function wait() {
    return Promise.resolve(something);
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda