React Hooks: 표시기 로드 및 오류 처리

7948 단어 react
React Hooks이 무엇인지, 여기에 useStateuseEffect 후크가 자세히 설명되어 있습니다.

이 블로그 기사는 useEffect를 사용하여 오류를 처리하고 표시기를 로드하는 방법에 관한 것입니다. 이 기사는 how to fetch data with React hooks에서 사용된 예제의 연속입니다.

💰: Start your cloud journey with $100 in free credits with DigitalOcean!

알림: 특정 주제가 있는 hackernews.com에서 기사를 가져와서 해당 기사에 대한 링크가 있는 목록에 결과 기사를 표시하려고 합니다. HackerNews에는 Algolia에서 제공하는 검색 API가 있으며 쿼리할 수 있습니다. 쿼리 문자열로 원하는 대로 사용할 수 있습니다. 저는 react 를 사용합니다. HackerNews API는 공개되고 무료이며 잘 문서화되어 있습니다Search Hacker News.

지금까지 코드:

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const res = await fetch(
        'https://hn.algolia.com/api/v1/search?query=react',
      );
      const json = await res.json();
      setData(json.hits);
    };
    fetchData();
  }, [setData]);

  return (
    <ul>
      {data.map(item => (
        <li key={item.ObjectId}>
          <a href={item.url}>{item.title}</a>
        </li>
      ))}
    </ul>
  );
}

export default App;


로딩 표시기를 추가하는 방법

To display a loading spinner or similar we have to know the current state of data fetching.

So we just add another state hook (useState) to handle the isLoading state and,

const [isLoading, setIsLoading] = useState(false);

set the state of isLoading based on the data fetching.

// before fetching data
setIsLoading(true);
// when data is fetching
setIsLoading(true);

Now, let's add it to the overall code example.

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      const res = await fetch(
        'https://hn.algolia.com/api/v1/search?query=react',
      );
      const json = await res.json();
      setData(json.hits);
      setIsLoading(false);
    };
    fetchData();
  }, [setData]);

  return (
    <React.Fragment>
      {isLoading ? (
        <p>Loading ...</p>
      ) : (
        <ul>
          {data.map(item => (
            <li key={item.ObjectId}>
              <a href={item.url}>{item.title}</a>
            </li>
          ))}
        </ul>
      )}
    </React.Fragment>
  );
}

export default App;

Code explanation: When the effect is called for data fetching (component mounts), the loading state is set to true. Once the request resolves, the loading state is set to false again.

데이터를 가져올 때 오류를 처리하는 방법

Proper handling of errors should be considered in every project, since the server could be not responding (maintenance, hardware problems, ...) or the request is missing some parameters or... . Think of error handling as a mandatory item on your project todo list.

Error handling with useEffect is just another state, hence another useState hook. We set the error state, when an error occurs. This is usually done in a try/catch statement, when working with async/await. You can also add the error message response from the API to your error state, for this example it will be just a boolean flag.

We add the useState for hasError and

const [hasError, setHasError] = useState(false);

set the state in the try/catch statement.

const fetchData = async () => {
  setIsLoading(true);
  setHasError(false);
  try {
    const res = await fetch(
      'https://hn.algolia.com/api/v1/search?query=react',
    );
    const json = await res.json();
    setData(json.hits);
  } catch (error) {
    setHasError(true);
  }
  setIsLoading(false);
};

Now let's combine this to the overall code example:

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsLoading(true);
      setHasError(false);
      try {
        const res = await fetch(
          'https://hn.algolia.com/api/v1/search?query=react',
        );
        const json = await res.json();
        setData(json.hits);
      } catch (error) {
        setHasError(true);
      }
      setIsLoading(false);
    };
    fetchData();
  }, [setData]);

  return (
    <React.Fragment>
      {hasError && <p>Something went wrong.</p>}
      {isLoading ? (
        <p>Loading ...</p>
      ) : (
        <ul>
          {data.map(item => (
            <li key={item.ObjectId}>
              <a href={item.url}>{item.title}</a>
            </li>
          ))}
        </ul>
      )}
    </React.Fragment>
  );
}

export default App;

Code explanation: The error state is reset every time the useEffect hook runs (component mounts).

TL;DR

  • Loading indicators increase UX and are easy to implement with useState.
  • Error handling should be a mandatory step in your project.
  • Error handling can be done easily with a useState hook.

Thanks for reading and if you have any questions , use the comment function or send me a message .

If you want to know more about React React Tutorials .

참조(그리고 큰 감사):

ReactJS , Dave Ceddia , Robin Wieruch

좋은 웹페이지 즐겨찾기