0

I have that code :

const FetchingApi = (props) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(true);
    //const [data, loading] = useFetch("myURL");
    useEffect(() => {
        fetch("myurl.json", { mode: 'no-cors', method: 'GET'}).then(response => {
            console.log(response.json())    
            return response.json()
        })
    }, [])   
    return (
        <>
            <div>
                Hello World !
            </div>
        </>
    )
}

export default FetchingApi;

I see in the developer console a 200 code which means it works but I see the variable response.json() such as :

Promise { <state>: "pending" }
​
<state>: "rejected"
<reason>: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

I don't know why ...

Could you help me please ? ​ I precise that myurl.json contains a JSON file and it works when I put in a JSON Validator

2 Answers 2

1

You can use React hooks for storing data. Use useState hook to store data.

Example:

import React, { useEffect, useState } from "react";

const App = () => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchData = async () => {
    setLoading(true);
    try {
      const URL =
        "https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=aud";
      const options = {
        method: "GET",
        "Content-Type": "application/json",
        Accept: "application/json"
      };
      const response = await fetch(URL, options);
      const data = await response.json();
      setData(data);
      setLoading(false);
    } catch (error) {
      setError(error);
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  if (loading) {
    return <p> Loading </p>;
  }

  if (error) {
    return <p style={{ color: "red" }}> {JSON.stringify(error)} </p>;
  }

  return (
    <div>
      <h1> Test </h1>
      <h1>{JSON.stringify(data)}</h1>
    </div>
  );
};
export default App;
Sign up to request clarification or add additional context in comments.

Comments

0

you should add headers:

  headers : { 
    'Content-Type': 'application/json',
    'Accept': 'application/json'
   }

and you should add another then for the case you are reading from a json file,

the full code should look like this:

const FetchingApi = (props) => {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(true);
    //const [data, loading] = useFetch("myURL");
    useEffect(() => {
        fetch("myurl.json", { mode: 'no-cors', method: 'GET',      
            headers : { 
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            }
       }).then(response => {
            console.log(response.json())    
            return response.json()
        })
         .then(myJson => {
            console.log(myJson);
            return myJson;
          });
    }, [])   
    return (
        <>
            <div>
                Hello World !
            </div>
        </>
    )
}

export default FetchingApi;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.