I’m trying to fetch an object from a server and then use that object’s variables in another function so that I can render them out. This is a React project for School. In previous versions I can get the object within the final function but I am unable to access the points within the object.
async function getAMZN() { //Can I make this proccess hit without needeing a full refresh
try {
const response = await fetch("http://127.0.0.1:31324/AMZN", {mode:"no-cors"});
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(`Could not get data: ${error}`);
}
}
async function AMZNuseState(){
const [AMZN, changeAMZN] = React.useState([getAMZN()])
return (
<span>
<h1>AMZN</h1>
<p>Price: {AMZN.price} </p>
<p>Volume: {AMZN.volume} </p>
<p>Last Five: </p>
</span>
)
};
I have a couple versions of this. Using the useState seemed to have the most promise but obviously it doesn’t quite work. In theory the getAMZN() returns an object with a stock price and volume. that function works in other versions. the AMZNuseState() would use useState to get the object so that way I can use its data.
2
Answers
The
getAMZN
is an asynchronous function, which returnPromise
, if you pass it as a parameter foruseState
, you just set the initial value to aPromise
, you need to useuseEffect
to invoke thegetAMZN
and withthen
function ( which will execute after the Promise resolved ), pass the result tosetAMZN
i think because the getAMZN is an asynchronous function and it return a promise so in useState you are initiali it with a promise so you need to use then to acess the data .