Home > OS >  I have a problem with fetching data with useEffect
I have a problem with fetching data with useEffect

Time:12-23

here is my code.

import React from 'react'
import { useEffect, useState } from 'react';
import './style.css'

function App(){

  let api = ("https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
      "x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
    }
  })

  useEffect(()=>{


    (async function(){
      let data = await fetch(api).then(res=>res.json());
      console.log(data);
    })();
  },[api]);
return(
  <div>Test</div>
);

};
export default App;

this is the error i am gettting.

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

it works with other simple api calls like "https://www.breakingbadapi.com/api/" but it doesn't work with this api i am using, i am not sure why.

CodePudding user response:

let api = ("https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
        "x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
    }
})

You're using the comma operator, so api will only contain the object that is present after the url.

Store this as an object or an array:

const api = ["https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
    "method": "GET",
    "headers": {
        "x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
        "x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
    }
}]


function App() {
    useEffect(() => {
        (async function () {
            const [url, options] = api;
            let data = await fetch(url, options).then(res => res.json());
            console.log(data);
        })();
    }, []); // this can be empty as api is outside and doesn't change

    return (
        <div>Test</div>
    );

};
  • Related