React/Zustand

Zustand를 활용(4): 여러 컴포넌트 간 상태 공유

atomicdev 2024. 10. 15. 13:24
728x90

비동기 작업과 Zustand

Zustand 비동기 작업

내용:

  1. 비동기 작업을 처리하기 위한 상태 관리: 비동기 작업은 주로 API 호출, 데이터베이스 접근과 같은 외부 데이터를 가져오는 작업을 포함합니다. Zustand는 이러한 비동기 작업을 처리할 수 있도록 간단한 상태 관리 기능을 제공합니다.
  2. Zustand에서 비동기 작업(fetch API 등) 다루기: 비동기 작업은 async/await 구문을 사용하여 처리됩니다. Zustand의 상태 저장소에 비동기 작업을 추가하면 컴포넌트 간에 데이터를 손쉽게 공유할 수 있습니다. 이를 통해 API 호출 후 상태를 업데이트하고 UI에 반영할 수 있습니다.

실습:

1. API 데이터를 Zustand로 관리하는 예제

// store.js
import create from 'zustand';

const useStore = create((set) => ({
  data: [],
  loading: false,
  error: null,
  fetchData: async () => {
    set({ loading: true });
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/todos');
      const data = await response.json();
      set({ data, loading: false });
    } catch (error) {
      set({ error: 'Failed to fetch data', loading: false });
    }
  },
}));

export default useStore;

2. API 호출 후 상태 업데이트하여 데이터 렌더링

// App.js
import React, { useEffect } from 'react';
import useStore from './store';

function App() {
  const { data, loading, error, fetchData } = useStore();

  useEffect(() => {
    fetchData(); // 컴포넌트가 렌더링될 때 API 호출
  }, [fetchData]);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>{error}</p>;

  return (
    <div>
      <h1>Todo List</h1>
      <ul>
        {data.map((item) => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;

3. 코드 설명:

  • useStore 훅에서 fetchData 함수를 통해 비동기 작업을 처리합니다.
  • API가 성공적으로 데이터를 가져오면, Zustand의 상태가 set 함수를 통해 업데이트되어 컴포넌트가 다시 렌더링됩니다.
  • App 컴포넌트에서는 데이터를 로드 중일 때, 성공적으로 로드했을 때, 오류가 발생했을 때 각각 다른 UI를 표시합니다.
728x90