Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have a problem with fetching data with useEffect

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/&quot; but it doesn’t work with this api i am using, i am not sure why.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
    );

};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading