0

I have this component which uses useState const [answers, setAnswerFunction] = useState(options);

Once the answers state has been updated in this component I would like to use the updated state and display it in another component. Is this possible?

I had a look at a similar question which says to use useContext I have not looked into this yet as I have never used it (Is it possible to share states between components using the useState() hook in React?) but I wondered if there would be a simpler way?

Code:

const QuestionBox = ({
  question,
  options,
  correct,
  incrementScore,
  incrementResponse,

}) => {
  const [response, setResponse] = useState(""); 
  const [answers, setAnswerFunction] = useState(options);

  const computeAnswer = answer => {
    if (answer === correct) {
      setResponse("correct");
      incrementScore();
      incrementResponse();
    } else {
      setResponse("sorry wrong!");
      incrementResponse();
    }
  };

  return (
    <div className="questionBox">
      <div className="question"> {question} </div>
      {answers.map((answer, index) => {
        return (
          <button
            key={index}
            className="answerBtn"
            type="button"
            onClick={() => {
              setAnswerFunction([answer]); 
              computeAnswer(answer); 
            }}
          >
            {answer}
          </button>
        );
      })}
      {response === "correct" ? (
        <div className="correctResponse"> {response} </div>
      ) : (
        <div className="wrongResponse"> {response} </div>
      )}
    </div>
  );
};
export default QuestionBox;



I want to display the state from the component abover answers here on Result card via the prop userAnswer:


const ResultCard = ({
  score,
  getQuestions,
  qbank,
  userAnswer
}) => {
  return (
    <div>
      <div>You scored {score} out of 5! </div>

      <div className="playBtnBox">
        <button className="playBtn" type="button" onClick={getQuestions}>
          Play again
        </button>
      </div>

      <div>
        {qbank.map((questionObject) => {
          return (
            <div>
              <div className="questionBox"> {questionObject.question}</div>
              <div className="resultCardCorrect"> Correct Answer: {questionObject.correct}</div>

            </div>
          );
        })}
      </div>
      <div className="resultCardCorrect"> Your Answer: {userAnswer}</div>
    </div>
  );
};

export default ResultCard;


Angela Inniss
  • 359
  • 1
  • 2
  • 18
  • Lifting the state up seems the only simple solution for your problem. – Rahul May 13 '20 at 16:51
  • [This question](https://stackoverflow.com/questions/53451584/is-it-possible-to-share-states-between-components-using-the-usestate-hook-in-r) does a good job of answering your question. I have used context to solve this issue in past when the two components have a different parent component. – Alvaro Castelan May 13 '20 at 16:52

0 Answers0