Making a back button using previous state of the array index

185 views Asked by At

I'm making a back button for a decision tree. The tree is made out of an array and its index. Right now, yes or no will take them to a different part of the array index as a response. I'm trying to find a way to capture the previous useState array indexes to connect them with an onClick back button.

not all of the array is here, just to keep it short.

const responses = [
    
    {
      id: 1,
      questionText: "Is the account data entry?",
      answerOptions: [
        { answerText: "No", isCorrect: false },
        { answerText: "Yes", isCorrect: true, jumpToQuestion: 6 },
      ],
      notes: [
      ],
    },
    {
      id: 2,
      questionText: "Is this customer 1 or 2?",
      answerOptions: [
        { answerText: "No", isCorrect: false },
        { answerText: "Yes", isCorrect: true, jumpToQuestion: 7 },
      ],
      notes: [
      ],
    },
    {
      id: 3,
      questionText: "Is the caller",
      answerOptions: [
        { answerText: "Power of Attorney/Conservator", isCorrect: true, jumpToQuestion: 15 },
        { answerText: "Lawyer", isCorrect: true, jumpToQuestion: 13 },
        { answerText: "Emergency Responder", isCorrect: true, jumpToQuestion: 14 },
        { answerText: "Wanting to make a payment", isCorrect: true, jumpToQuestion: 18 },
        { answerText: "Death/Cancellation/Takeover", isCorrect: false, jumpToQuestion: 19},
      ],
      notes: [
      ],
    },
    {
      id: 4,
      questionText: "Is it someone with a signed 'Name Add Form' on file?",
      answerOptions: [
        { answerText: "No", isCorrect: false },
        { answerText: "Yes", isCorrect: true, jumpToQuestion: 7 },
      ],
      notes: [
      ],
    },
    {
      id: 5,
      questionText: "Is it someone who is verbally authorized by a verified account holder to speak with Alder?",
      answerOptions: [
        { answerText: "No", isCorrect: false, jumpToQuestion: 12 },
        { answerText: "Yes", isCorrect: true, jumpToQuestion: 7 },
      ],
      notes: [
      ],
    },

  const [currentQuestion, setCurrentQuestion] = useState(0);

  const handleAnswerButton = (jumpToQuestion) => {
    const nextQuestion = jumpToQuestion || currentQuestion + 1;
    setCurrentQuestion(nextQuestion);
  }
1

There are 1 answers

0
Thales Kenne On

Just store the previous question id like you're doing with the jumpToQuestion.

const [previousQuestionId, setPreviousQuestionId] = useState(0); //Initialize at whatever index you need

Then in your handleAnswerButton:

const handleAnswerButton = (jumpToQuestion) => {
    setPreviousQuestionId(currentQuestion.id)

    const nextQuestion = jumpToQuestion || currentQuestion + 1;

    setCurrentQuestion(nextQuestion);
  }

Let me know if that works :)