action_results.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import { PayloadAction, createAsyncThunk, createSlice } from "@reduxjs/toolkit";
  2. import { useDispatch } from "react-redux";
  3. export enum ResultType {
  4. idle = 'idle',
  5. ing = 'ing',
  6. success = 'success',
  7. fail = 'fail',
  8. retry = 'retry',
  9. countdown = 'countdown'
  10. }
  11. interface ResultState {
  12. title: string | null;
  13. type: any | ResultType.idle;
  14. seconds: number | 0;
  15. }
  16. const initialState: ResultState = {
  17. title: null,
  18. type: ResultType.idle,
  19. seconds: 0
  20. }
  21. const resultTime = 1;
  22. const countdownTime = 5;
  23. const resultSlice = createSlice({
  24. name: 'result',
  25. initialState,
  26. reducers: {
  27. checkStart(state) {
  28. state.type = ResultType.ing;
  29. },
  30. checkSuccess(state) {
  31. state.type = ResultType.success;
  32. },
  33. checkFail(state) {
  34. state.type = ResultType.fail;
  35. },
  36. checkRetry(state){
  37. state.type = ResultType.retry;
  38. },
  39. checkCountdown(state,action: PayloadAction<any>) {
  40. state.title = action.payload;
  41. state.type = ResultType.countdown;
  42. },
  43. checkCountdownEnd(state) {
  44. state.type = ResultType.idle;
  45. state.seconds = 0;
  46. },
  47. resetStatus(state) {
  48. state.type = ResultType.idle;
  49. state.seconds = 0;
  50. }
  51. }
  52. }
  53. );
  54. export const { checkStart, checkSuccess, checkFail, checkCountdownEnd, checkCountdown, resetStatus,checkRetry } = resultSlice.actions;
  55. export default resultSlice.reducer;
  56. export const setResult = createAsyncThunk('result/action', async (payload: {isSuccess:boolean}, { dispatch }) => {
  57. if (payload.isSuccess) {
  58. dispatch(checkSuccess());
  59. setTimeout(() => {
  60. var count = countdownTime;
  61. dispatch(checkCountdown(count));
  62. var timer = setInterval(()=>{
  63. count--;
  64. dispatch(checkCountdown(count));
  65. if (count<0){
  66. clearInterval(timer);
  67. dispatch(resetStatus())
  68. }
  69. },1000)
  70. }, resultTime*1000);
  71. }
  72. else {
  73. dispatch(checkFail());
  74. setTimeout(()=>{
  75. dispatch(resetStatus());
  76. },resultTime*1000)
  77. }
  78. });