如何Async/Await使用useEffect来获取数据?

How to Async/Await using useEffect for fetching data?

我查了一些问题,但没能解决这个问题。我正在尝试将 async and await 添加到我正在获取数据的 useEffect 中。

另外,如何在数据加载前添加一个简单的加载文本?

我的代码:

import { useEffect, useState } from "react";

import { Link } from "react-router-dom";

import SanityClient from "sanity.client";

const AllPosts = () => {
  const [posts, setPosts] = useState(null);

  useEffect(() => {
    const postsQuery = `
    *[_type == 'post'] {
      _id,
      title,
      slug,
      mainImage {
        alt,
        asset -> {
          _id,
          url
        }
      }
    }
  `;

    SanityClient.fetch(postsQuery)
      .then((data) => setPosts(data))
      .catch(console.error);
  }, []);

  return (
    <>
      <h2>Blog Posts</h2>
      <h3>Welcome to my blog</h3>
      {posts &&
        posts.map((post) => (
          <Link key={post._id} to={`/blog/${post.slug.current}`}>
            <img src={post.mainImage.asset.url} alt={post.mainImage.alt} />
            <h2>{post.title}</h2>
          </Link>
        ))}
    </>
  );
};

export default AllPosts;

下面是异步等待的方法。你试过这个吗?

import { useEffect, useState } from "react";

import { Link } from "react-router-dom";

import SanityClient from "sanity.client";

const AllPosts = () => {
  const [posts, setPosts] = useState(null);

  const fetchData = async (postsQuery) => {
    try {
      const data = await SanityClient.fetch(postsQuery);
      if (data) {
        setPosts(data);
      }
    } catch(error) {
      console.log(error);
    }
  }

  useEffect(() => {
    const postsQuery = `
    *[_type == 'post'] {
      _id,
      title,
      slug,
      mainImage {
        alt,
        asset -> {
          _id,
          url
        }
      }
    }
  `;

    fetchData(postsQuery);
  }, []);

  return (
    <>
      <h2>Blog Posts</h2>
      <h3>Welcome to my blog</h3>
      {posts &&
        posts.map((post) => (
          <Link key={post._id} to={`/blog/${post.slug.current}`}>
            <img src={post.mainImage.asset.url} alt={post.mainImage.alt} />
            <h2>{post.title}</h2>
          </Link>
        ))}
    </>
  );
};

export default AllPosts;