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
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.
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;
}
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);
}