Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.0k views
in Technique[技术] by (71.8m points)

How to access external json data via url link in ReactJS

I am trying to access the data I have via external url, but I am not getting any output. In my solution I want to use React hooks so first, I pointed to the url

const dataInfo = "secretURLwithJSONData";

than I am using useState and useEffect functions in my component

const reactComponent = () => {
    const [userData, setUserData] = useState({});

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

    const getDataInfo = async () => {
        const response = await fetch(dataInfo);
        const jsonData = await response.json();
        setUserData(jsonData);
    };

And the last step is that I am pointing out at the data from JSON

<h5 >{userData.name}</h5>

Example of JSON in url:

{
  "data": [
    {
      "attributes": {
        "name": "Name"
      }
    }
    ]   
}

As you can see is is an array of objects, so there are of course more data, but it should give you an idea of the structure.

jsonData in console:

jsonData HERE


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have a few issues:

  1. You're accessing the data wrong (at least given the example above)
  2. You're accessing it before it's made available

Since you're dealing with an async operation (fetching data) you need to make sure your data exists before accessing it in JSX:

{userData.data ? <h5>{userData.data[0].attributes.name}</h5> : 'No data yet'}

And since your data is an array, you'll need to map through it (untested code, but you get the idea):

{userData.data ? {userData.data.map((data) => 
 <h5 >
  {data.attributes.name}</h5> 
)}
: 'No data yet'}

Keep in mind you're also accessing a deeply nested object there, so you should make sure all those levels exist, unless you trust your API enough that it won't change.

Using Optional Chaining is useful for this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...