Home > Mobile >  Get json file with ajax in react
Get json file with ajax in react

Time:03-26

I need to get JSON file with AJAX. I have my data locally in data.json. It looks like

[
  {
    "id": 0,
    "favourite": false,
    "name": "Gilbert Morton",
    "age": 30,
    "phone": "(369) 432-9206",
    "image": "sheep",
    "phrase": "Japman somam mes lizmasapa om zefopi ki wa ogju mofrajnir denba uc famoso opeipu woul.",
    "video": "shoe"
  },
  {
    "id": 1,
    "favourite": true,
    "name": "Jeffery Davidson",
    "age": 57,
    "phone": "(415) 670-6901",
    "image": "pig",
    "phrase": "Lejtefup boc hi ricge tela mo ragdi vutomeh kuhup veosubu pe ceso juhzustum ipagagcub fu."
  }
]

I am doing in the following way

async function getUser() {
    try {
      const response = await fetch("/data.json");
      const data = await response.json();
      console.log(response);
      console.log(data);
    } catch (error) {
      console.error(error);
    }
  }
  useEffect(() => {
    getUser();
},[])

I got response, status 200, but on data Unexpected token < in JSON at position 0. What I do wrong?

CodePudding user response:

I tried your code and it's working properly however I see an issue with your useEffect you got an extra bracket after the dependency array

also if you're using create react app make sure your json file is located inside your public folder

  • Related