schoon
schoon

Reputation: 3324

How do I retrieve value from async function in react?

Pretty new to this stuff, so probably doing this wrong, but it is my understanding to get a number (in this case startTypeValue) rather than the promise of a number, I need a function something like this:

 render() {...
    var startTypeValue: number =0;

    const startType = async (accessToken: string): Promise<Number> => {

      const value = await startTypeGetPromise(accessToken) // how to unwrap the value inside this  promise
      startTypeValue= value.valueOf();
      console.log("inner"+JSON.stringify(startTypeValue, undefined, 2));
      return startTypeGetPromise(accessToken)
    }

   const startTypePromise = startType(this.props.accessToken);
   console.log("outer"+JSON.stringify(startTypeValue, undefined, 2));

inner gives 1 which is correct but outer gives 0. ( startTypeGetPromise(accessToken) does a DB call which returns 1). Is this because it is async and doesn't get the correct value in time? Or am I not setting the outer value correctly?

EDIT: following @ultrayam I added:

class myPage extends React.Component<MyPageProps> {
  constructor(props: MyPageProps| any) {
    super(props);
    this.state = { startTypeValue: 0 };
  }

but I try:

this.state['startTypeValue']

and I get:

Element implicitly has an 'any' type because expression of type '"startTypeValue"' can't be used to index type 'Readonly<{}>'.

Upvotes: 0

Views: 903

Answers (3)

ultrayam
ultrayam

Reputation: 144

The startType function is returning a Promise. To receive the resolved value of your async function you can use then.

For example,

async function add(a,b) {
  return a + b;
}

let x = add(3, 6);
console.log(x); // Promise

add(3, 6).then(ret => console.log(ret)); // 9

In your class component,

import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: 0 };
  }
  
  add = async (a,b) => {
    return a + b;
  }
  
  // set state
  componentDidMount() {
    this.add(1,2).then(ret => this.setState({value: ret}));
  }
  
  render() {
    return <h1>{this.state.value}</h1>;
  }
}

export default App;

Upvotes: 1

Jessy CHARLOT
Jessy CHARLOT

Reputation: 11

The following code works for me on CodeSandbox. You must use setState for update a value. Can you try this ? I hope it will helps you

    export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <MyClass />
    </div>
  );
}

async function add(a, b) {
  return a + b;
}

class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = { startTypeValue: 0 };
  }

  loadResult = async () => {
    await add(3, 6).then((ret) => this.setState({startTypeValue: ret}));
  };

  // set state
  componentDidMount() {
    this.loadResult();
  }

  render() {
    return <h1>{this.state.startTypeValue}</h1>;
  }
}

Upvotes: 1

Faruk
Faruk

Reputation: 111

async function add (a,b) {
    const result = await a+b;
    return result
}

let test = add(5,10)
const[value, setValue] = useState(0); // using React State
test1.then(res => setState(res))
console.log(value) // will give you the result

Upvotes: 0

Related Questions