Home > Software design >  i want to know how can i use this JSON data HackNews
i want to know how can i use this JSON data HackNews

Time:02-04

Hi bros I'm making SPA react program I have some question

const [storyIds, setStoryIds] = useState([]);
  const list = [];
  useEffect(() => {
    Top_API().then((res) => {
      this.res = res.data.slice(0, 3);
      this.res.forEach((ele) => {
        axios
          .get("https://hacker-news.firebaseio.com/v0/item/"   ele   ".json")
          .then((res) => {
            list.push({
              id: res.data.id,
              title: res.data.title,
              url: res.data.url,
              user: res.data.by,
              score: res.data.score
            });
            setStoryIds(list);
          });
      });
    });
  }, []);

this is my code i want to print this api data I print JSON data like this

{JSON.stringify(storyIds[0])}

This code works well. However, from the storyIds[1] arrangement, it is not visible on the screen. I checked that it was output from the console.

And when i go to a different page, If i outputting the contents of my code array, an error occurs that the array cannot be found when you return to the page. ex)

{JSON.stringify(storyIds[0].title)}

If you write like the code above, an error occurs that the array is not defined.

I've been trying to solve this situation for three days now. But I couldn't find a way. Help me.

The code that you print on the screen is as follows.

<div className="n1">
          
          <a href={JSON.stringify(storyIds[0])}>
            {JSON.stringify(storyIds[0])}
          </a>
          <br />
          by: {JSON.stringify(storyIds[0])}
        </div>
        <div className="n2">{JSON.stringify(storyIds[1])}</div>
        <div className="n3">{JSON.stringify(storyIds[2])}</div>
      </div>

the data look's like

[{"id":30186326,"title":"Facebook loses users for the first time","url":"https://www.washingtonpost.com/technology/2022/02/02/facebook-earnings-meta/","user":"prostoalex","score":994},{"id":30186894,"title":"In second largest DeFi hack, Blockchain Bridge loses $320M Ether","url":"https://blockworks.co/in-second-largest-defi-hack-ever-blockchain-bridge-loses-320m-ether/","user":"CharlesW","score":400}] 

how can i print this API response my screen?

CodePudding user response:

The problem with your code is that you are resetting the storyIds state to the single element being loaded by the GET call on every loop cycle.

Try to change it like this:

const [storyIds, setStoryIds] = useState([]);

useEffect(async () => {
  const list = [];

  let apiResponse = await Top_API();
  apiResponse = apiResponse.data.slice(0, 3);
  apiResponse.forEach(async (ele) => {
    const { data } = await axios.get(
      'https://hacker-news.firebaseio.com/v0/item/'   ele   '.json'
    );
    const { id, title, url, by, score } = data;
    list.push({ id, title, url, user: data.by, score });
  });

  setStoryIds(list);
}, []);

CodePudding user response:

You need to use async await for waiting for response from API

const [storyIds, setStoryIds] = useState([]);
  const list = [];
  useEffect(() => {
    Top_API().then((res) => {
      this.res = res.data.slice(0, 3);
      this.res.forEach(async (ele) => {
       await axios
          .get("https://hacker-news.firebaseio.com/v0/item/"   ele   ".json")
          .then((res) => {
            list.push({
              id: res.data.id,
              title: res.data.title,
              url: res.data.url,
              user: res.data.by,
              score: res.data.score
            });
          });
       setStoryIds(list);
      });
    });
  }, []);
  •  Tags:  
  • Related