Frontend ๐Ÿ“š/React

[Node] Dialogflow API๋ฅผ ํ™œ์šฉํ•œ ์ฑ—๋ด‡ ์‚ฌ์ดํŠธ - 4. Redux์— ๋ฉ”์„ธ์ง€ ์ €์žฅ

leejaejae 2024. 8. 19. 17:46

โ˜… ์ด ๋ถ€๋ถ„์€ Chatbot๊ณผ์˜ ๋ฉ”์„ธ์ง€ ๋‚ด์šฉ์„ Redux์— ์ €์žฅํ•˜๋Š” React ๋ถ€๋ถ„์œผ๋กœ ํ•„์š”์— ์˜ํ•ด ์ƒ๋žต ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค!

// ๊ธฐ์กด์˜ Chatbot.js ํŒŒ์ผ์— ์ถ”๊ฐ€

import { useDispatch } from "react-redux";
import { saveMessage } from "../_actions/message_actions";

function Chatbot() {
  const dispatch = useDispatch();
  ...
  dispatch(saveMessage(conversation));
  ...
}

 

โœ๏ธ ./client/.../_reducers ํด๋”

// index.js

import { combineReducers } from 'redux';
import message from './message_reducer';

const rootReducer = combineReducers({
    message,
});

export default rootReducer;
// message_reducer.js

import { SAVE_MESSAGE } from "../_actions/types";

export default function (state = { messages: [] }, action) {
  switch (action.type) {
    case SAVE_MESSAGE:
      return {
        ...state,
        messages: state.messages.concat(action.payload),
      };
    default:
      return state;
  }
}

 

โœ๏ธ ./client/.../_actions ํด๋”

// types.js

export const SAVE_MESSAGE = 'save_message';
// message_actions.js

import { SAVE_MESSAGE } from "./types";

export function saveMessage(dataToSubmit) {
  return {
    type: SAVE_MESSAGE,
    payload: dataToSubmit,
  };
}

โ˜… ๋”ฐ๋ผํ•˜๋ฉฐ ๋ฐฐ์šฐ๋Š” ๋…ธ๋“œ, ๋ฆฌ์•กํŠธ ์‹œ๋ฆฌ์ฆˆ - ์ฑ—๋ด‡ ์‚ฌ์ดํŠธ ๋งŒ๋“ค๊ธฐ ๊ฐ•์˜๋ฅผ ์ฐธ๊ณ ํ•ฉ๋‹ˆ๋‹ค.