Home > Enterprise >  React nested fetch json
React nested fetch json

Time:08-10

Is there a way to nest fetch calls and add all the (promises) returned data object info one useState? I am trying to do that using the spread operator in the following way as seen below. Now, I know I could simply create another UseState and store the 2nd fetch data but I just wonder if it's possible to create one object of data from nested fetch calls.

const DetailsPage = () => {

  const params = useParams();
  const { id } = params;

  const [data, setData] = useState(null)

  const fetchData = () => {

   fetch(url1, options)
    .then(response => response.json())
      .then((data) => {
       setData(data.results)
        fetch(url2, options)
         .then(response => response.json())
           .then((data) => {
            setData([...data, data.results])
          })
           .catch(err => console.error(err))
      })
      .catch(err => console.error(err))
    }

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

CodePudding user response:

The simplest solution is to use async-await syntax

const fetchData = async () => {
    const res1 = await fetch(url1, options);
    const json1 = await res1.json();
    doStuffWith(json1);
    const res2 = await fetch(url2, options);
    // and so on

BTW the second fetch doesn't seem to depend on the first one, why not do them in parallel?

const [res1, res2] = await Promise.all([fetch(url1, options), fetch(url2, options)]);

CodePudding user response:

try it:

 const fetchData = () => {
   fetch(url1, options)
    .then(response => response.json())
      .then((data1) => {
        fetch(url2, options)
         .then(response => response.json())
           .then((data2) => {
             setData([data1.results, data2.results])
          })
           .catch(err => console.error(err))
      })
      .catch(err => console.error(err))
    }

  • Related