0

Game.js

import axios from 'axios'
import React from 'react'
import { useEffect, useState } from 'react'

const Game = ({gameTitle}) => {
    const [game, setGame] = useState({
        description: '',
        requirements: '',
        game: null,
        date: '',
        title: '',
        id: ''
    })

    useEffect(() => {
        const href = window.location.href
        const title = href.split('/')[4]
        // href = http://localhost:3000/games/Red%20Dead%20Redemption%202
        // title = Red Dead Redemption 2

        axios.get(`http://localhost:8000/api/games/${title}`) 
        .then(res => res.data)
        .then(data => {
            setGame({ 
                id: data[0].id,
                description: data[0].description,
                requirements: data[0].requirements,
                game: data[0].game,
                date: data[0].date,
                title: data[1].title,
            })
        })
        console.log(game)
            
    }, [])

    return (
    <>
        {game.id}
    </>

    )
}

export default Game

What I should receive

{
    "id": 1,
    "description": "A game",
    "requirements": "Memory: 16GB, Gpu: RTX 3090",
    "game": "/media/media/games/game.zip",
}

{
"title": "Red Dead Redemption 2"
}

What I receive

{
  "description": "",
  "requirements": "",
  "game": null,
  "date": "",
  "title": "",
  "id": ""
}

I'm pretty sure this problem is because of how I'm getting the title from window.location.href, but if not then I really dont know what could be wrong here... whenever I ctrl + s in vs code, for some reason I receive the data that I'm expecting, any help is appreciated.

Lun
  • 229
  • 3
  • 11
  • 1
    Changes to state from `useState` are not reflected immediately. Please check out the answer to https://stackoverflow.com/a/54069332/368697 for a thorough explanation. – Ross Allen Jul 30 '21 at 20:02

0 Answers0