Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use async / await in React JS?

I started programming in React Native, and I got used to use the syntax:

async myFunction(){     ...     return await otherFunction(); } 

But I don't know how to make it compatible with React JS and React Native in a shared package. How can I accomplish this so that it works in both platforms?

Thanks!

like image 423
Santiago Bendavid Avatar asked Jul 13 '16 16:07

Santiago Bendavid


People also ask

Can I use async in react?

Introduction to React-AsyncReact Async is compatible with almost all the data fetching libraries and APIs, including Fetch API, Axios, and GraphQL. Also, it works well with React Native too.

Why async await is used in react JS?

An async function is a function declared with the async keyword, and the await keyword is permitted within it. The async and await keywords enable asynchronous, promise-based behavior to be written in a cleaner style, avoiding the need to explicitly configure promise chains.

Can I use async await in JavaScript?

The await operator is used to wait for a Promise . It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.


2 Answers

If you building using create-react-app it's been available since v0.2.3

https://github.com/facebookincubator/create-react-app/releases/tag/v0.2.3

It can be used inside a Component like this

class App extends Component {   constructor(props) {     super(props);     this.state = { message: '' };   }    async componentDidMount() {     this.setState({ message: 'loading...' });     let d = await getData('/posts/1');     this.setState({ message: d });   }    render() {     let { message } = this.state;     return (       <div className="App">         <p className="App-intro">           { message }         </p>       </div>     );   } } 

See:

https://github.com/facebookincubator/create-react-app/issues/1024

like image 149
Tim Arney Avatar answered Sep 20 '22 11:09

Tim Arney


React Native ships with Babel and some Babel presets, whereas React on the web is just React related code.

If you want to use async/await on the web today you'll need Babel and the correct transforms: https://babeljs.io/docs/plugins/transform-async-to-generator/

or the stage-1 presets, which is fairly common in React apps today. http://babeljs.io/docs/plugins/preset-stage-1/

like image 41
azium Avatar answered Sep 20 '22 11:09

azium