Home > Software engineering >  Rendering async promises through function components
Rendering async promises through function components

Time:02-25

Sorry if the post is duplicated i just find examples for class components.

I have this code:


    export const getUniPrice = async () => {
        const pair = await Uniswap.Fetcher.fetchPairData(HOKK, Uniswap.WETH[ETH_CHAIN_ID]);
        const route = new Uniswap.Route([pair], Uniswap.WETH[ETH_CHAIN_ID]);
        const priceUni = route.midPrice.toFixed(9);
        return priceUni
    }

It does work, answer me the promise object:


[[PromiseState]]: "fulfilled"
[[PromiseResult]]: "1106278.001628948"

What i would like to know is, how can i properly work with this object in order to be able to render it through function components? I'm doing something like this which obviously will not work because react doesn't render objects.

const Price = () => {
    const { state, dispatch } = useContext(AppContext);
    return(<>
        {state.dex === 'uni' ? getUniPrice() : state.dex === 'cake'
            ? getCakePrice() : getMDexPrice()
    }
    </>)
 } 

Could someone give me a hint? This function is running outside a function component so I can't just use useState

CodePudding user response:

You're right. The result of getUnitPrice() is a Promise, not a value, so what React does is it prints out the stringified version of that Promise. If you need the fulfilled value, you need a state value that will re-render the page if updated. Something like this:

const [price, setPrice] = useState('');

useEffect(() => {
  getUnitPrice().then((p) => setPrice(p));
}, []);

...

<div>Price: {price}</div>

If you're using a class component, you can initialize the state the same way like this:

state = {
  price: '',
}
async componentDidMount() {
  const p = await getUniPrice();
  this.setState({ price: p });
}

  • Related