Go Pro Sign Up Login

Buy Now and unlock this series

$

39

.99

$

29

.99

yours forever

Become a Pro and unlock everything

$

24

.99

per month

API Calls with ComponentWillMount

This video is about #8 API Calls with ComponentWillMount

Downloads

Become a pro to download code and videos

Comments

Nathan

over 1 year ago [edited]

If you want to use a functional component, use useEffect() instead of componentWillMount():

export default function PostIndex() {
  const [posts, setPosts] = useState();

  //Must use useEffect in non-page component

  useEffect(async () => {
    let res = await fetch(`${Config.apiUrl}/wp-json/wp/v2/posts`);
    res = await res.json();
    setPosts(res);
  }, []);

  return (
    <div>
      <h1>Post Index</h1>
      <ul>
        { !!posts && posts.map((post) => (
          <li key={posts.id}>
            <Link href={`/posts/${post.id}`}>
              <a>{post.title.rendered}</a>
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

Want to join the conversation?

Become a Pro member today!