0

I want to read the json data from url, put it in an empty array, put it in a react component, and print it out. However, if you put the json data in the result array and output it as console.log, only the empty array is output. Is it wrong to push the array?

Also, I want to repeat this url 100 times and print it out in the order of many counts. For example, count: 15 {Json content}. Thank you.

let result = [];

fetch("http:// ~ ").then(res => { return res.json()}).then(data => result.push(data)).then(()=>console.log(result));

lsm
  • 43
  • 4
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – FZs Aug 26 '22 at 07:22

3 Answers3

0

The last .then is redundant. Put the console.log(result) in the same function as result.push(data) and it should work. You do need to add brackets to the function, though, since it will no longer be a "one-liner".

fetch("http:// ~ ")
  .then(res => res.json())
  .then(data => {
    result.push(data);
    console.log(result);
  });

Edit: The way that .then works is that it executes once a promise is resolved. res.json() returns a promise. Your own function (data => result.push(data)) does not return a promise. So using .then on your own function doesn't make any sense. I hope this clears things up for you.

Edit 2:

Since this is in react, you shouldn't do let result = [] and result.push(data). Instead, you should do something like this:

const [result, setResult] = React.useState();

And within your own function, change result.push(data) to this:

setResult([...result, data]);
Emil Karlsson
  • 1,000
  • 1
  • 7
  • 16
  • thanks! but still put the fetched data in the result array outside and open it to the console.log from the fetch outside, still get an empty array. How do i solve this problem? – lsm Aug 26 '22 at 07:21
  • You're using react, so I would suspect that you need to use `useState`. I'll update my answer soon. – Emil Karlsson Aug 26 '22 at 07:26
0

You need to use useEffect and or useState hook to trigger a rerender.

let result = [];

useEffect(()=>{
fetch("http:// ~ ")
  .then(res => res.json())
  .then(data => {
    result.push(data);
    console.log(result);
  });
},[])

not this will trigger a re-render once your data is fetched

Deniz Karadağ
  • 751
  • 3
  • 8
0

try this,

import { useState, useEffect } from "react";

export default function App() {

  const [state, setState] = useState([])

  useEffect(() => { 
      fetch("http:// ~ ")
        .then(res => res.json())
        .then(data => setState([...state, data]));
  }, [])

  return (
    <div className="App">{JSON.stringify(state)}</div>
  );
}
Vinod Liyanage
  • 945
  • 4
  • 13