Search code examples
reactjsasync-awaites6-promise

How to convert promise based function to async await?


I am fetching data using promise and setting the data using useState as shown below. How can use async/await instead of promise then?

    // App

    import React, { useState } from 'react';
    import fetchEmails from 'data/fetchEmails';

    const App = () => {
      const [date, setDate] = useState('');
      const [data, setData] = useState([]);

      return (
        <div>
          <div>
            <input
              value={date}
              onChange={setDate}}
            />
            <button onClick={() => fetchEmails(date, setData)}>Get data</button>
          </div>
          <div>
            {/* show data here, please ignore this part */}
            {data.map(d => <div>{d.text}</div>)}
          </div>
        </div>
      );
    };

    // fetchEmails

    const fetchEmails = (date, setData) => {
      fetch(
        `http://localhost:9000/?date=${date}`
      )
        .then((res) => res.json())
        .then((res) => setData(res))
        .catch((err) => console.log(err));
    };

    export default fetchEmails;

Solution

  • you can do like this

     const fetchEmails = async (date, setData) => {
      let res = await fetch(`http://localhost:9000/?date=${date}`);
      console.log(res);
      setData(res);
    };