0

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<{}>'.
4
  • render method isn't supposed to make async call yet as of v17 of react. You should use a lifecyle method to make the api call and store the data in state Commented Apr 8, 2021 at 13:32
  • Er...could you give an example, please? Commented Apr 8, 2021 at 13:36
  • I'd ignore the .then() answers and just make a useEffect() with an async function, so you can use await instead of then chaining (which is a little outdated). Your component should render a loading... screen until the useEffect() has finished. Commented Apr 8, 2021 at 13:57
  • Thanks, do you have an example? Commented Apr 8, 2021 at 14:09

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, so how do I extract the value of ret in your example?
You can create a state and this.setState in then. More on setState here reactjs.org/docs/react-component.html#setstate.
Thanks. I have tried the above but still don't know how to get the value.
Use this.state.value in the render function
1

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>;
  }
}

Comments

0
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

5 Comments

Thanks but I get: React Hook "useState" cannot be called in a class component
Use State inside the class component then state = { value: 0 }
Sorry, not sure what you mean?
Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please edit your question and explain how it answers the specific question being asked. See How to Answer.
Why does javascript have to change its fundamental thesis for core operation every 8 to 16 months for the last decade? Are they trying to obfuscate or is it an artifact of evolution?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.