Skip to content

Instantly share code, notes, and snippets.

@NickFoden
Created April 9, 2020 14:21
Show Gist options
  • Save NickFoden/4ea80173b3845d852603e99559eaf76a to your computer and use it in GitHub Desktop.
Save NickFoden/4ea80173b3845d852603e99559eaf76a to your computer and use it in GitHub Desktop.
useEffect async promise
import React, { useState, useEffect } from "react";
import { myPromise } from "../api";
const index = () => {
const [data, setData] = useState([]);
useEffect(async () => {
const result = await myPromise();
setData(result);
}, []);
return (
<div>
<ul>
{data.map((item) => (
{/* assumes each object in array has key property */}
<li key={item.key}>{item}</li>
))}
</ul>
</div>
);
};
export default index;
@NickFoden
Copy link
Author

NickFoden commented Apr 9, 2020

import React, { useState, useEffect } from "react";
import { myPromise } from "../api";

const index = () => {
  const [data, setData] = useState([]);
  useEffect(async () => {
    const result = await myPromise();
    setData(result);
  }, []);

  useEffect( () => {
      const promiseFetch = fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json()).then(result => setData(result)) 
     return promiseFetch()
 }, []);

  return (
    <div>
      <ul>
        {data.map((item) => (
          {/* assumes each object in array has key property */}
          <li key={item.key}>{item}</li>
        ))}
      </ul>
    </div>
  );
};

export default index;
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment