Debug School

rakesh kumar
rakesh kumar

Posted on

How to get random question using redux pattern after login in react js

How to open different type of popup model randomly using redux pattern
How to open popup model after verify otp
Step1: in verfy.otp
Using a dispatch function call a state management system redux store

 dispatch(openFeedbackModal())
Enter fullscreen mode Exit fullscreen mode
 if (result.data.status === true) {
        localStorage.setItem("User", JSON.stringify(result.data.user))
        console.log("userdata")
        console.log(result.data.user)
        setupUser(result.data.user)
        const { accessToken, refreshToken } = result.data
        console.log(accessToken)
        setCookie("accessToken", accessToken, 8000, "/")
        setCookie("refreshToken", refreshToken, 864000, "/")
        await setAccessToken(accessToken)
        await setRefreshToken(refreshToken)
        dispatch(openFeedbackModal())
        navigate("/")
      } else {
        navigate("/signup")
      }
    } catch (error) {}
  }
Enter fullscreen mode Exit fullscreen mode

Image description

export const openFeedbackModal = () => {
  return (dispatch) => {
    const myArray = ["OPEN_MULTIPLE_MODAL", "OPEN_SUBJECTIVE_MODAL"]
    const randomIndex = Math.floor(Math.random() * myArray.length)
    const randomString = myArray[randomIndex]
    dispatch({ type: randomString })
  }
}
Enter fullscreen mode Exit fullscreen mode
 case OPEN_SUBJECTIVE_MODAL:
      return { ...state, isSubjectiveModalOpen: true }
    case OPEN_MULTIPLE_MODAL:
      return { ...state, isMultipleModalOpen: true }
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

export const getSubjectiveQuestion = () => {
  return async (dispatch) => {
    dispatch({ type: GET_SUBJECTIVE_QUESTION_BEGIN })
    try {
      const response = await authFetch.get("/feedback/subjective")
      console.log(response)
      dispatch({ type: GET_SUBJECTIVE_QUESTION_SUCCESS })
      return response.data.question
    } catch (error) {
      console.log(error)
      dispatch({ type: GET_SUBJECTIVE_QUESTION_ERROR })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
export const getMultipleQuestion = () => {
  return async (dispatch) => {
    dispatch({ type: GET_SUBJECTIVE_QUESTION_BEGIN })
    try {
      const response = await authFetch.get("/feedback/multiple")
      // console.log(response)
      dispatch({ type: GET_SUBJECTIVE_QUESTION_SUCCESS })
      return response.data.question
    } catch (error) {
      console.log(error)
      dispatch({ type: GET_SUBJECTIVE_QUESTION_ERROR })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode
const getSubjectiveQuestion = async (req, res) => {
  const user = req.user._id

  let alreadyAnswered = await Feedback.find({ user: user }).select(
    "-_id question"
  )
  console.log("alreadyAnswered")
  console.log(alreadyAnswered)
  alreadyAnswered = alreadyAnswered.map((i) => {
    const id = i.question.toString()
    return id
  })
  console.log("alreadyAnswered1")
  console.log(alreadyAnswered)
  const questions = await Question.find({
    _id: { $nin: alreadyAnswered },
    type: "subjective",
  })
  console.log("alreadyAnswered3")
  console.log(questions)
  if (questions.length === 0) {
    const repeat = await Question.find({ type: "subjective" })

    res.status(200).json({ question: repeat[0] })
  } else {
    res.status(200).json({ question: questions[0] })
  }
}
Enter fullscreen mode Exit fullscreen mode
const getObjectiveQuestion = async (req, res) => {
  const user = req.user._id

  let alreadyAnswered = await Feedback.find({ user: user }).select(
    "-_id question"
  )
  console.log("alreadyAnswered")
console.log(alreadyAnswered)
  alreadyAnswered = alreadyAnswered.map((i) => {
    const id = i.question.toString()
    return id
  })
  console.log("alreadyAnswered1")
  console.log(alreadyAnswered)
  const questions = await Question.find({
    _id: { $nin: alreadyAnswered },
    type: "multiple",
  })
  console.log("alreadyAnswered3")
  console.log(questions)
  if (questions.length === 0) {
    const repeat = await Question.find({ type: "multiple" })

    res.status(200).json({ question: repeat[0] })
  } else {
    console.log("alreadyAnswered4")
    console.log(questions[0])
    res.status(200).json({ question: questions[0] })
  }
}
Enter fullscreen mode Exit fullscreen mode
 <Wrapper>
      <Modal
        show={isSubjectiveModalOpen}
        onHide={closeModal}
        aria-labelledby="contained-modal-title-vcenter"
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title>
            {isEditingQuestion ? "edit questions" : "subjective question"}
          </Modal.Title>
        </Modal.Header>
        <Modal.Body>
          {question && (
            <div>
              <p>{capitalizeFirstLetter(question.question)}</p>
              <FormRow
                name="answer"
                type="textarea"
                labelText={isEditingQuestion ? "enter new question" : "answer"}
                value={values.answer}
                handleChange={handleChange}
                required={true}
                // placeholder={"Add answer"}
              />
              <button className="btn" onClick={handleSubmit}>
                submit
              </button>
            </div>
          )}
        </Modal.Body>
      </Modal>
    </Wrapper>
Enter fullscreen mode Exit fullscreen mode
 <Wrapper>
      <Modal
        show={isMultipleModalOpen}
        onHide={closeModal}
        aria-labelledby="contained-modal-title-vcenter"
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title>
            {isEditingQuestion ? "edit question" : "objective question"}
          </Modal.Title>
        </Modal.Header>
        <Modal.Body>
          {!editingQuestion && (
            <Wrapper>
              {question && (
                <div>
                  <p>{capitalizeFirstLetter(question.question)}</p>

                  {question.options.map((q) => {
                    return (
                      <FormRow
                        name="option"
                        type="radio"
                        labelText={q}
                        handleChange={handleOptions}
                        value={q}
                      />
                    )
                  })}

                  <button className="btn" onClick={handleSubmit}>
                    submit
                  </button>
                </div>
              )}
            </Wrapper>
Enter fullscreen mode Exit fullscreen mode

============================================================
Another way

Image description

Image description

Define action types:

Image description

Create action creators:

Image description

Create a reducer to handle random opening of modals:

Image description

Connect components to Redux and dispatch random actions:

Image description

Image description

To open different types of popup modals randomly using the Redux pattern, you can follow these steps:

Set up your Redux store: Ensure that you have set up your Redux store with the required reducers and middleware (e.g., Redux Thunk) to handle asynchronous actions.

Define action types: Define action types for each type of popup modal you want to open. These action types will be used to identify which modal to open.

Create action creators: Create action creator functions for each action type. These functions will return actions with the corresponding action type.

Create a reducer: Set up a reducer to handle the actions dispatched to open different types of popup modals randomly. The reducer will update the state to indicate which modal is currently open.

Dispatch actions randomly: From your components, dispatch a random action to open a randomly chosen modal.

Here's a more detailed step-by-step guide with code examples:

Set up Redux store:

// redux/store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

export default store;
Enter fullscreen mode Exit fullscreen mode

Define action types:

// redux/actions.js
export const OPEN_MULTIPLE_MODAL = "OPEN_MULTIPLE_MODAL";
export const OPEN_SUBJECTIVE_MODAL = "OPEN_SUBJECTIVE_MODAL";
Enter fullscreen mode Exit fullscreen mode

// Add more action types for other modals if needed
Create action creators:

// redux/actions.js
import { OPEN_MULTIPLE_MODAL, OPEN_SUBJECTIVE_MODAL } from './actionTypes';

export const openMultipleModal = () => ({ type: OPEN_MULTIPLE_MODAL });
export const openSubjectiveModal = () => ({ type: OPEN_SUBJECTIVE_MODAL });
// Add more action creators for other modals if needed
Enter fullscreen mode Exit fullscreen mode

Create a reducer to handle random opening of modals:

// redux/reducers.js
import { OPEN_MULTIPLE_MODAL, OPEN_SUBJECTIVE_MODAL } from './actionTypes';

const initialState = {
  modalType: null,
};
Enter fullscreen mode Exit fullscreen mode
const modalReducer = (state = initialState, action) => {
  switch (action.type) {
    case OPEN_MULTIPLE_MODAL:
    case OPEN_SUBJECTIVE_MODAL:
      return { ...state, modalType: action.type };
    default:
      return state;
  }
};

export default modalReducer;
Enter fullscreen mode Exit fullscreen mode

Connect components to Redux and dispatch random actions:

// YourComponent.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { openMultipleModal, openSubjectiveModal } from './redux/actions';

const YourComponent = () => {
  const modalType = useSelector(state => state.modalType);
  const dispatch = useDispatch();

  const handleOpenRandomModal = () => {
    const randomIndex = Math.floor(Math.random() * 2); // Change to the number of modal types you have
    if (randomIndex === 0) {
      dispatch(openMultipleModal());
    } else {
      dispatch(openSubjectiveModal());
    }
  };

  return (
    <div>
      <button onClick={handleOpenRandomModal}>Open Random Modal</button>

      {modalType && (
        <div>
          {modalType === OPEN_MULTIPLE_MODAL && <div>Content of Multiple Modal</div>}
          {modalType === OPEN_SUBJECTIVE_MODAL && <div>Content of Subjective Modal</div>}
        </div>
      )}
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

In this example, we set up a Redux store with a modalReducer that handles actions to open different types of modals randomly. The YourComponent component connects to the store using useSelector to access the modalType state and useDispatch to dispatch random actions to open random modals. The handleOpenRandomModal function generates a random index and dispatches a random action based on that index. Depending on the modalType, the component conditionally renders the content of the corresponding modal.

Top comments (0)