0

I'm making a Quiz Game, and I need to send the results of the quiz since Play.js to QuizSummary.js

My Play.js looks like:

import React, { Component, Fragment} from "react";
import withRouter from "../../withRouter"

//[More code]

class Play extends Component {


//[More code]

    endGame = () => {
        const { navigate } = this.props

        alert('Quiz has ended!');
        const { state } = this;
        const playerStats = {
            score: state.score,
            numberOfQuestions: state.numberOfQuestions,
            numberOfAnsweredQuestions: state.numberOfAnsweredQuestions,
            correctAnswers: state.correctAnswers,
            wrongAnswers: state.wrongAnswers,
            fiftyFiftyUsed: 2 - state.fiftyFifty,
            hintsUsed: 5 - state.hints
        };
        console.log(playerStats)
        setTimeout(() => {
            navigate('/play/quizSummary', {state:{playerStats}});
        }, 1000);
    }


//[Rest of the code]

The navigate funtion is defined on another component to be able the useNaviegate() hook works in my class component.

This is the code:

import { useNavigate } from "react-router-dom";

const withRouter = WrappedComponent => props => {
    const navigate = useNavigate();


return (
    <WrappedComponent
    {...props}
    {...{navigate}}
    />
);
};

export default withRouter

And my QuizSummary.js looks like:

import React, {Component} from "react";

class QuizSummary extends Component {
    constructor (props) {
        super(props);
        this.state = {
            score: 0,
            numberOfQuestions: 0,
            numberOfAnsweredQuestions: 0,
            correctAnsewers: 0,
            wrongAnswers: 0,
            usedHints: 0,
            usedFiftyFifty: 0
        };
    }
    render () {
        console.log(this.props.playerStats)
        return (
            <h1>Hello from Quiz QuizSummary</h1>
        );
    }
}
export default QuizSummary;

I want that when I finish the game, I redirect to the summary page (that works fine) & send the data to display the results. But when I check-it the console displays like "undefined".

How I can send the data in endGame() function to the QuizSummary.js?

  • 2
    What is `navigate` in the `endGame` function? What is `playerStats` in the `QuizSummary` component? Can you [edit] to include complete code? See [mcve]. In all likelihood your issues will be resolved if you used React function components and current React practices. Class components have been effectively deprecated since about 2018 when React hooks were released. – Drew Reese Jun 30 '23 at 21:01
  • The `playerStats` in the `QuizSummary` it pretends to be the same as in the Play component. I declare it in `Play.js` and I try to send using `navigate`. – Genís Gisbert Jul 01 '23 at 07:55

0 Answers0