hasanhatem's avatar

I can't fetch data when refresh the page with react js

Hello,

I have a simple react js component, i just fetch data from laravel api. When I working on the code i get the data and every thing ok. BUT when i refresh the page i got error and blank page.

react-refresh-runtime.development.js:315 Uncaught TypeError: Cannot read properties of undefined (reading 'body')

this is the component

import { Box, Card, Paper, Container, Stack, Typography, Grid, Button } from "@mui/material"
import { useState, useEffect } from "react"
import { generateLink } from "../utils/config"

const QuizGame = () => {

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

    useEffect(() => {
        const questionsData = async () => {
            await fetch(generateLink('questions/5')).then(async (response) => {
                let data = await response.json();

                setQuestions([...data.questions]);
            })
        }

        questionsData();
    }, [])

    return (
        <>
            <Typography variant="h4" component="h2" textAlign="center">
                {questions[currentQuestion].body}
            </Typography>

            <Grid container justifyContent="center">
                <Grid item xs={8}>
                    <Grid container spacing={{ xs: 2, md: 3 }} columns={{ xs: 4, sm: 8, md: 12 }}>
                        {questions[currentQuestion].answers.map((answer) => (
                            <Grid item xs={6} textAlign="center" key={answer.id}>
                                <Button variant="outlined">
                                    {answer.body}
                                </Button>
                            </Grid>
                        ))}
                    </Grid>
                </Grid>
            </Grid>

        </>
    )
}

export default QuizGame
0 likes
0 replies

Please or to participate in this conversation.