Home > Mobile >  How can I do to store a value in a variable from an external API using React.js?
How can I do to store a value in a variable from an external API using React.js?

Time:10-28

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

CodePudding user response:

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;

CodePudding user response:

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;
  • Related