Redux Toolkit을 이용한 자바스크립트 앱의 푸시 알림 기능

push_notification

푸시 알림은 사용자에게 중요한 정보를 전달하는데 유용한 기능입니다. 이번 블로그에서는 Redux Toolkit을 이용하여 자바스크립트 앱에 푸시 알림 기능을 추가하는 방법을 알아보겠습니다.

Redux Toolkit 소개

Redux Toolkit은 Redux를 사용하기 쉽게 만들어주는 공식적인 패키지입니다. Redux의 기본 개념을 이해하고 있어야 하지만, Toolkit은 보일러플레이트 코드를 줄여줌으로써 Redux 개발을 좀 더 간편하게 만듭니다.

푸시 알림을 위한 Redux Store 설정

먼저 Redux Store에 푸시 알림 관련 상태를 저장하기 위한 Slice를 생성합니다. Slice는 Redux Toolkit에서 제공하는 상태와 액션을 관리하는 단위입니다. 다음과 같이 알림 관련 상태와 액션을 정의해줍니다:

// notificationSlice.js

import { createSlice } from '@reduxjs/toolkit';

export const notificationSlice = createSlice({
  name: 'notification',
  initialState: {
    notifications: [],
  },
  reducers: {
    addNotification: (state, action) => {
      state.notifications.push(action.payload);
    },
    removeNotification: (state, action) => {
      state.notifications = state.notifications.filter(notification => notification.id !== action.payload);
    },
  },
});

export const { addNotification, removeNotification } = notificationSlice.actions;

export default notificationSlice.reducer;

위 코드에서 notifications는 푸시 알림들을 저장하는 배열입니다. addNotification은 새로운 알림을 추가하고, removeNotification은 특정 알림을 제거하는 액션입니다.

알림 추가와 제거

이제 알림을 추가하고 제거하기 위해 컴포넌트에서 Redux 액션을 디스패치해야 합니다. 다음과 같이 알림을 추가하는 컴포넌트를 예시로 작성해보겠습니다:

// AddNotification.js

import React from 'react';
import { useDispatch } from 'react-redux';
import { v4 as uuidv4 } from 'uuid';
import { addNotification } from './notificationSlice';

const AddNotification = () => {
  const dispatch = useDispatch();

  const handleAddNotification = () => {
    const notification = {
      id: uuidv4(),
      message: '새로운 알림입니다.',
    };

    dispatch(addNotification(notification));
  };

  return (
    <button onClick={handleAddNotification}>알림 추가</button>
  );
};

export default AddNotification;

위 컴포넌트는 handleAddNotification 함수가 호출될 때마다 새로운 알림을 생성하고, Redux 액션을 디스패치하여 알림을 추가합니다. 실제로는 UI에서 알림을 보여주는 컴포넌트를 구현해야 하지만, 이 예시에서는 단순화된 버튼으로 대체했습니다.

제거하는 방법도 유사하게 작성할 수 있습니다. 단지 handleRemoveNotification 함수에서 removeNotification 액션을 디스패치하면 됩니다.

결론

Redux Toolkit을 사용하여 자바스크립트 앱에 푸시 알림 기능을 추가하는 방법을 알아보았습니다. Redux Toolkit을 통해 Redux 개발이 간편해졌으며, Slice를 이용하여 알림에 대한 상태와 액션을 관리하는 방식을 살펴보았습니다. 알림을 추가하고 제거하는 컴포넌트를 구현하는 방법에 대해서도 간단히 알아보았습니다.

#redux #javascript #redux-toolkit #푸시알림