skip to Main Content

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


  1. The getAMZN is an asynchronous function, which return Promise, if you pass it as a parameter for useState, you just set the initial value to a Promise, you need to use useEffect to invoke the getAMZN and with then function ( which will execute after the Promise resolved ), pass the result to setAMZN

    import React, { useState, useEffect } from 'react';
    
    async function getAMZN() {
        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}`);
        }
    }
    
    function AMZNuseState() {
        const [AMZN, setAMZN] = useState({ price: 0, volume: 0 }); // Initialize with default values
    
        useEffect(() => {
            getAMZN().then(data => {
                if (data) {
                    setAMZN(data);
                }
            });
        }, []);
    
        return (
            <span>
                <h1>AMZN</h1>
                <p>Price: {AMZN.price}</p>
                <p>Volume: {AMZN.volume}</p>
                <p>Last Five: </p>
            </span>
        );
    };
    
    export default AMZNuseState;
    
    Login or Signup to reply.
  2. 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 .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search