Guide to executing a fetch request prior to another fetch in React Native

I am currently working on a project using React Native. One issue I have run into is that all fetch requests are being executed simultaneously. What I actually need is for one fetch to wait until the previous one has completed before using its data.

Specifically, I want to utilize the idTitle from the first fetch in the second fetch. However, due to them being executed concurrently, this is not possible.

function SongScreen({ route }) {

  const { textArtist, textSong } = route.params;

  const geniusUrl = 'https://api.genius.com';

  const [isLoading, setLoading] = useState(true);

  const [idTitle, setIdTitle] = useState([]);
  const [idVideoYT, setIdVideoYT] = useState([]);
       
  useEffect(async () => {
    fetch(geniusUrl + '/search?q=' + textSong, {
      headers: { 'Authorization': 'Bearer ' + geniusToken }
    })
      .then((response) => response.json())
      .then((json) => {
        for (const value of json.response.hits) {
          if ((value.result.title.toLowerCase() == textSong.toLowerCase()) &&
            (value.result.primary_artist.name.toLowerCase() == textArtist.toLowerCase())) {
            setIdTitle(value.result.api_path)
            setIdArtist(value.result.primary_artist.api_path)
          }
        }
      })
      .catch((error) => { AlertView(), setModalVisible(true) })
      .finally(() => setLoading(false));
  }, []);

          
  useEffect(() => {
    fetch(geniusUrl + idTitle, {
      headers: { 'Authorization': 'Bearer ' + geniusToken }
    })
      .then((response) => response.json())
      .then((json) => {
        for (const value of json.response.song.media) {
          if (value.provider == 'youtube')
            setIdVideoYT(value.url)
        }
      })
      .catch((error) => alert(error)) //{ AlertView(), setModalVisible(true) })
      .finally(() => setLoading(false));
  }, []);
    
  return (
    //.....
  )
}

In my attempts to solve this issue by concatenating the fetch calls like so, I encountered the same error:

useEffect(async () => {
    fetch(geniusUrl + '/search?q=' + textSong, {
      headers: { 'Authorization': 'Bearer ' + geniusToken }
    })
      .then((response) => response.json())
      .then((data) => {
        for (const value of data.response.hits) {
          if ((value.result.title.toLowerCase() == textSong.toLowerCase()) &&
            (value.result.primary_artist.name.toLowerCase() == textArtist.toLowerCase())) {
            setIdTitle(value.result.api_path)   
            setIdArtist(value.result.primary_artist.api_path)   
          }
        }
      })
      .then(
        fetch(geniusUrl + idTitle, {
          headers: { 'Authorization': 'Bearer ' + geniusToken }
        })
          .then((response) => response.json())
          .then((json) => {
            for (const value of json.response.song.media) {
              if (value.provider == 'youtube')
                setIdVideoYT(value.url)
            }
          })
          .catch((error) => alert(error)) //{ AlertView(), setModalVisible(true) })
          .finally(() => setLoading(false))
      )
      .catch((error) => { AlertView(), setModalVisible(true) })
      .finally(() => setLoading(false));
  }, []);

I made another attempt by adding a then inside the if block, but it produced an error stating that the then variable could not be found:

useEffect(async () => {
fetch(geniusUrl + '/search?q=' + textSong, {
  headers: { 'Authorization': 'Bearer ' + geniusToken }
})
  .then((response) => response.json())
  .then((data) => {
    for (const value of data.response.hits) {
      if ((value.result.title.toLowerCase() == textSong.toLowerCase()) &&
        (value.result.primary_artist.name.toLowerCase() == textArtist.toLowerCase())) {
         setIdTitle(value.result.api_path)
         setIdArtist(value.result.primary_artist.api_path)

          then(() => fetch(geniusUrl + value.result.api_path, {
            headers: { 'Authorization': 'Bearer ' + geniusToken }
          })
            .then((response) => response.json())
            .then((json) => {
              for (const value of json.response.song.media) {
                if (value.provider == 'youtube')
                  setIdVideoYT(value.url)
              }
            })
            .catch((error) => alert(error))
            .finally(() => setLoading(false))
          )

      }
    }
  })
  .catch((error) => alert(error))
  .finally(() => setLoading(false));


 }, []);

For convenience, I decided to include all three fetches within the same useEffect. Although I attempted to use await for the third fetch, it always ended up in the catch block:

useEffect(async () => {

fetch(geniusUrl + '/search?q=' + textSong, {
  headers: { 'Authorization': 'Bearer ' + geniusToken }
})
  .then((response) => response.json())
  .then((data) => {
    for (const value of data.response.hits) {
      if ((value.result.title.toLowerCase() == textSong.toLowerCase()) &&
        (value.result.primary_artist.name.toLowerCase() == textArtist.toLowerCase())) {
        setIdTitle(value.result.api_path)   //for third fetch
        setIdArtist(value.result.primary_artist.api_path)  
      }
    }
  })
  .catch((error) => { AlertView(), setModalVisible(true) })
  .finally(() => setLoading(false));


  fetch(lyricsUrl + textArtist + '/' + textSong)
    .then((response) => response.json())
    .then((text) => setDataLyrics(text.lyrics))
    .catch((error) => { AlertView(), setModalVisible(true) })
    .finally(() => setLoadingLyrics(false));


try {
  let response = await fetch(geniusUrl + idTitle, {
    headers: { 'Authorization': 'Bearer ' + geniusToken }
  });
  let id = await response.json();
  for (const value of id.response.song.media) {
    if (value.provider == 'youtube')
      setIdVideoYT(value.url)
  }
}
catch (error) {
  alert(error);
}
setLoading(false);

}

Answer №1

React Native operates on a JavaScript foundation, allowing it to execute code sequentially in a non-blocking manner.

To address this:

const output = await fetch(URL, payload)

or

fetch(anotherUrl, Payload)
.then(response => response.json)
.then(response => {
Perform an action
 fetch(anotherUrl)... etc
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you explain the meaning of this AJAX code snippet?

I've been researching online for information, but I'm struggling to find any details about the AJAX code snippet that I'm using: function getEmployeeFilterOptions(){ var opts = []; $checkboxes.each(function(){ if(this.checke ...

Discover the sub strings that fall between two specified regular expressions

I am looking for a way to extract substrings from a string that are between two specified regex patterns. Here are a few examples: My $$name$$ is John, my $$surname$$ is Doe -> should return [name, surname] My &&name&& is John, my & ...

Is it possible to maintain variables across a session with numerous users when utilizing socket.io?

My code structure is designed as follows: //Route Handler that triggers when a user 'creates a session' app.post('/route', async (req, res) => { let var1 = []; let var2 = []; io.on('connection', (socket) => ...

Assistance with the Chakra UI Range Slider in React

I could use some help figuring out where exactly to implement my OnChange and Map functions for mapping JSON data into a Range Slider. Everything seems to be rendering correctly, but I keep encountering an error when I try to move the slider: Unhandled Ru ...

Using Javascript's .replace() method to preserve HTML elements

This is a JavaScript function I wrote function replaceCharacters(text_input){ return text_input .replace(/O/g, 0) .replace(/I/g, 1) .replace(/o/g, 0) .replace(/i/g, 1) .replace(/t/g, 4) .replace(/d/g, 9) ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

Alternate routing based on conditions in Angular

I've used the "$urlRouterProvider.otherwise('{route here}')" syntax in angular to create a catch-all route in Angular UI-Router. One thing I'm curious about is whether it's possible to have conditional "otherwise" routing based o ...

Adding an overlay to a material UI table row: Step by step guide

My code is rendering a row in the following format: `<TableRow key={row.name} > <TableCell>{row.empId}</TableCell> <TableCell>{row.userId}</TableCell> <TableCell>{row.name}</TableCell> <TableCell>{r ...

Encountering an error with my electron application built using create-react-app

While I'm working on my project, my electron window is showing this error message. TypeError: fs.existsSync is not a function getElectronPath ../node_modules/electron/index.js:7 4 | var pathFile = path.join(__dirname, 'path.txt') 5 | ...

Notifying with Jquery Alert after looping through routes using foreach loop

I am trying to create a jQuery alert message that displays after clicking on a dynamically generated button in the view using a foreach loop. The issue I am facing is that only the first button in the loop triggers the alert, while the subsequent buttons ...

Dealing with issues escaping unicode characters in JavaScript

Whenever I need to load data from an external file based on a specific event, I make use of the following jQuery code: $("#container").load("/include/data.php?name=" + escape(name)); An issue arises when the JavaScript variable "name" contains Unicode ch ...

Encountering a 403 error when attempting to upload files from Angular to a Micron

I have encountered an issue while attempting to upload multiple files to the Micronaut Rest API. The uploading process works seamlessly with Postman and Swagger in the Micronaut Rest API, but when using the Angular app, the POST method throws a 403 HTTP er ...

Controller is not being triggered by Ajax method when there is a decimal value

I am currently working on implementing a time registration feature in my web application. Users can select the project they worked on and enter the number of hours spent on that project. Everything is functioning properly until users start adding half-hou ...

The WebView.HitTestResult method is currently only receiving <img src> elements and not <a href> elements

I am attempting to open a new window in the Android browser using "_blank". I have set up an event listener for this purpose. mWebView.getSettings().setSupportMultipleWindows(true); mWebView.setWebChromeClient(new WebChromeClient() { ...

Showcasing diverse content with an Angular Dropdown Menu

I'm currently developing an angular application, and I've encountered a difficulty in displaying the user's selection from a dropdown menu. To elaborate, when a user selects a state like Texas, I want to show information such as the period, ...

Storing information in Firebase using React.js

When storing an object in Firebase, I expected the structure to be as shown in the image below. However, what I received was a generated running number as a key. This is the code I used to store the object in Firebase: var location = []; location.push({ ...

Storing input data in a JavaScript array instead of sending it through an AJAX request

I've been grappling with this issue for quite some time now, and I just can't seem to wrap my head around it. While there are a few similar solutions out there, none of them address my exact problem. Here's the scenario: I have a form where ...

Selecting from a variety of options presented as an array of objects

I am currently working on a component that allows users to select roles: https://i.stack.imgur.com/bnb9Y.png export const MultipleSelectChip = ({ options, label, error, onRolesUpdate, }: Props) => { const theme = useTheme(); const [selected ...

Choose a procedure to reset to the original setting

I'm attempting to achieve something that seems straightforward, but I'm having trouble finding a solution. I have a <select> tag with 5 <option> elements. All I want to do is, when I click a button (which has a function inside of it), ...

Unable to render canvas element

Hey guys, I'm trying to display a red ball on the frame using this function but it's not working. I watched a tutorial and followed the steps exactly, but I can't seem to figure out what's wrong. Can someone please help me with this? I ...