[ad_1]
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("Hello");
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??)
[ad_2]