Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

47
Views
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

7 months ago ยท Juan Pablo Isaza
1 answers
Answer question

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);
}
7 months ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
ยฉ 2023 PeakU Inc. All Rights Reserved.