shows error message when request req fails

This commit is contained in:
ajaythapliyal
2023-02-22 10:02:05 +05:30
parent 41742dccd3
commit 1fc9d61325
6 changed files with 41 additions and 6 deletions

View File

@@ -1,6 +1,7 @@
import { forwardRef } from 'react';
import Avatar from '../Avatar';
import { MESSAGE_TYPE } from './conversationModels';
import Alert from './../assets/alert.svg';
const ConversationBubble = forwardRef<
HTMLDivElement,
@@ -14,11 +15,26 @@ const ConversationBubble = forwardRef<
<div
ref={ref}
className={`flex rounded-3xl ${
type === 'QUESTION' ? '' : 'bg-gray-1000'
type === 'ANSWER'
? 'bg-gray-1000'
: type === 'ERROR'
? 'bg-red-1000'
: ''
} py-7 px-5 ${className}`}
>
<Avatar avatar={type === 'QUESTION' ? '👤' : '🦖'}></Avatar>
<p className="ml-5">{message}</p>
<div
className={`ml-5 flex items-center ${
type === 'ERROR'
? 'rounded-lg border border-red-2000 p-2 text-red-3000'
: ''
}`}
>
{type === 'ERROR' && (
<img src={Alert} alt="alert" className="mr-2 inline" />
)}
<span>{message}</span>
</div>
</div>
);
});

View File

@@ -5,7 +5,7 @@ export function fetchAnswerApi(
apiKey: string,
): Promise<Answer> {
// a mock answer generator, this is going to be replaced with real http call
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
let result = '';
const characters =
@@ -18,7 +18,16 @@ export function fetchAnswerApi(
);
counter += 1;
}
resolve({ answer: result, query: question, result });
const randNum = getRandomInt(0, 10);
randNum < 5
? reject()
: resolve({ answer: result, query: question, result });
}, 3000);
});
}
function getRandomInt(min: number, max: number) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); // The maximum is exclusive and the minimum is inclusive
}

View File

@@ -1,4 +1,4 @@
export type MESSAGE_TYPE = 'QUESTION' | 'ANSWER';
export type MESSAGE_TYPE = 'QUESTION' | 'ANSWER' | 'ERROR';
export type Status = 'idle' | 'loading' | 'failed';
export interface Message {

View File

@@ -38,8 +38,12 @@ export const conversationSlice = createSlice({
type: 'ANSWER',
});
})
.addCase(fetchAnswer.rejected, (state) => {
.addCase(fetchAnswer.rejected, (state, action) => {
state.status = 'failed';
state.conversation.push({
text: 'Something went wrong. Please try again later.',
type: 'ERROR',
});
});
},
});