Adds mock conversation api layer, adds reducers to handle various asyc

state and wires it with conversation UI
This commit is contained in:
ajaythapliyal
2023-02-20 09:04:24 +05:30
parent 63859a814b
commit a036a6b979
7 changed files with 122 additions and 34 deletions

View File

@@ -1,6 +1,7 @@
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import store from '../store';
import { ConversationState, Message } from './conversationModels';
import { fetchAnswerApi } from './conversationApi';
import { Answer, ConversationState, Message } from './conversationModels';
// harcoding the initial state just for demo
const initialState: ConversationState = {
@@ -24,13 +25,21 @@ const initialState: ConversationState = {
{ text: 'what is ChatGPT', type: 'QUESTION' },
{ text: 'ChatGPT is large learning model', type: 'ANSWER' },
{ text: 'what is ChatGPT', type: 'QUESTION' },
{
text: 'ChatGPT is large learning model',
type: 'ANSWER',
},
{ text: 'ChatGPT is large learning model', type: 'ANSWER' },
],
status: 'idle',
};
export const fetchAnswer = createAsyncThunk<
Answer,
{ question: string },
{ state: RootState }
>('fetchAnswer', async ({ question }, { getState }) => {
const state = getState();
const answer = await fetchAnswerApi(question, state.preference.apiKey);
return answer;
});
export const conversationSlice = createSlice({
name: 'conversation',
initialState,
@@ -39,12 +48,30 @@ export const conversationSlice = createSlice({
state.conversation.push(action.payload);
},
},
extraReducers(builder) {
builder
.addCase(fetchAnswer.pending, (state) => {
state.status = 'loading';
})
.addCase(fetchAnswer.fulfilled, (state, action) => {
state.status = 'idle';
state.conversation.push({
text: action.payload.answer,
type: 'ANSWER',
});
})
.addCase(fetchAnswer.rejected, (state) => {
state.status = 'failed';
});
},
});
export const { addMessage } = conversationSlice.actions;
type RootState = ReturnType<typeof store.getState>;
export const selectConversation = (state: RootState) =>
state.conversation.conversation;
export const selectStatus = (state: RootState) => state.conversation.status;
export const { addMessage } = conversationSlice.actions;
export default conversationSlice.reducer;