What is the best way to utilize the useSWR hook when there are necessary logical operations to be performed on the response before proceeding with the next API call

I am currently utilizing the swr library in a Create React App and require the usage of the useSWR hook for data fetching that is both contingent and conditional. The specific task at hand involves:

  1. Making an API call to retrieve an id which will be used for a subsequent API call. This id can be found within either the upcomingEvents or passedEvents array.
  2. My preference is to obtain the id from the upcomingEvents array, but in cases where it is empty, I would then look into the passedEvents array.
  3. It is my intention to extract the first id from either array, thus using the initial index of either array is acceptable (e.g., upcomingEvents[0].id).
  4. Below is an illustration of the code snippet and the response received from the initial API call:
const { data: result } = useSWR(`${BASE_URL}/event/${searchEvent}`);
// The subsequent call will wait for the resolution of the first call before executing
const { data: event, error } = useSWR(() => `${BASE_URL}/project/${result.upcomingEvents[0].id}`);

The response obtained from the initial call, which contains the id required for the next call, might resemble this structure:

{
  "upcomingEvents": [{"id": "1234"}, {"id": "5678"}, {"id": "0909"}],
  "passedEvents": [{"id": "0987"}, {"id": "6543"}]
}

If I explicitly specify the id for the second API call as upcomingEvents[0].id (as shown in the above code example), the desired outcome is achieved.

My challenge lies in determining where to incorporate the logic that selects the appropriate id for the dependent second API call. I require this logic but am uncertain about its placement without violating the rules governing hooks utilization.

  const { data: result } = useSWR(`${BASE_URL}/event/${searchEvent}`);
  const { data: event, error } = useSWR(() =>
   result.upcomingEvents.length > 0
     ? `${BASE_URL}/project/${result.upcomingEvents[0].id}`
     : `${BASE_URL}/project/${result.passedEvents[0].id}`
  );

Answer №1

I have a solution that tackles this problem efficiently:

  • First, I suggest splitting the two useSWR requests into separate functions to manage them individually.
  • Secondly, ensure to pass a null key into the second useSWR() call when the value returned from the first useSWR function is falsy. By doing this, you will prevent the second fetch from executing if the first one is still in progress.

 const fetcher = url => fetch(url).then(r => r.json())
 
 const useEvents = () => {
  const { data } = useSWR(`${BASE_URL}/event/${searchEvent}`, fetcher);
  return data;
 };
 
 const useEventDetails = () => {
   const events = useEvents();
   let endpoint;

   if (!events) {
     endpoint = null
   }
   else {
    endpoint = events.upcomingEvents.length > 0 ?
     `${BASE_URL}/project/${result.upcomingEvents[0].id}`
     `${BASE_URL}/project/${result.passedEvents[0].id}`;
   }
   
   const { data } = useSWR(endpoint, fetcher);
   return data;
 }

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

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Creating a straightforward REST API in React with basic authentication

I am currently trying to learn how to implement react with a rest api, but I have encountered some issues with debugging and diagnosing the problem. I have been following a tutorial and adapted the code for my sample rest api response, however, I am only g ...

What is the best way to dynamically update a specific value within an object based on the current state in React/Next?

I have implemented a Context API where an object is set, and when the user clicks, the state changes. I need to update a specific value with the new state value. const initialState = { notification: false, setting: false, profile: false, } exp ...

Implement a click event for the X-Axis label in Angular 2 Highcharts

I'm currently facing a challenge with hand-rolling a solution that involves adding a click listener to an X-Axis label in a column chart using the HighCharts API within an Angular 2+ application. Here is what I have gathered so far: I am utilizing ...

Tips for accessing the value and text of an Angular Material mat-select through the use of *ngFor

When using a dropdown menu, I want to retrieve both the value and text of the selected option. View dropdown image Underneath the dropdown menu, I aim to display values in the format of "options: 'value' - 'selected option'". compone ...

Sending template reference from one Angular component to another

I have a main grid component that includes smaller grid-item components. The majority of these grid items navigate to a specific route when clicked. However, there is one particular item that should open a modal window instead of navigating. Is there a wa ...

What is the process for removing a registered user from Realm Object Server with the use of the Javascript library?

I have been searching online for a solution, but I haven't been able to find an answer. I am attempting to remove a user from ROS, however, I cannot locate a designated API for this task. The version of my realm-js is 1.10.3. If this feature does not ...

Use leaflet.js in next js to conceal the remainder of the map surrounding the country

I'm currently facing an issue and would appreciate some assistance. My objective is to display only the map of Cameroon while hiding the other maps. I am utilizing Leaflet in conjunction with Next.js to showcase the map. I came across a helpful page R ...

What could be causing all the flickering in this presentation?

Check out the jQuery slideshow I uploaded on my blog at robertmarkbramprogrammer.blogspot.com/2010/09/jquery-slideshow.html The slideshow is flickering in Chrome but looks fine in IE, Firefox, and even the standalone version. You can view it here: Here i ...

How to retrieve HTML attribute using D3 techniques

Looking to iterate through all rect nodes in the code snippet below: d3.selectAll("svg g rect") .on('mouseover', function (d) { console.log(this); }); When Console.log is executed, the following is printed: <rect class="cls" na ...

Transmit information via ajax and receive responses in json format

Looking to send a string and receive JSON format in return. The current method is functional but lacks the ability to return JSON code. $.ajax({ url: "getFeed.php", type: "post", data: myString }); Attempts to retrieve JSON string result in ...

What impact does setting a variable equal to itself within a Dom Object have?

Within my code example, I encountered an issue with image sources and hrefs in a HTML String named tinymceToHTML. When downloading this html String, the paths were set incorrectly. The original image sources appeared as "/file/:id" in the String. However, ...

Vue: event triggers malfunctioning and components unresponsive

I am new to Vue.js and I'm attempting to trigger an event from my grand-child component (card) to the child component (hand) and then to the parent component (main): card (emit play event) => hand (listen for play event and emit card-play event) => ...

Challenges with implementing MUI React Server-Side Rendering

We are in the process of implementing Server Side Rendering for an existing project that uses React-MUI. While we have successfully set up everything, we are facing an issue with styling. None of our CSS files are loading for the server side render. Inline ...

Use jQuery to refresh the jQuery sparkline chart after fetching data asynchronously

Background Utilizing the jquery.sparkline library to generate Pie Charts. The data for these charts is stored in an array. Upon initial page load, a web-service call is made (using .ajax) to fetch the data. The callback function associated with this call ...

"Struggling with a redux toolkit error - the API seems to be malfunctioning whenever I trigger

** I'm brand new to using Redux Toolkit and I'm encountering an issue. Can anyone help me figure out what the problem is? ** Image1 Image2 export const fetchUser = () => async (dispatch) => { try { dispatch({ type: " ...

Securing the IDs of Stripe customers and Firebase users through encryption

Do you think it's necessary to encrypt the Stripe customer ID within a NextJS environment? I have an API route in NextJS that updates the customer's email address using the Stripe Customer ID from a Firestore database (using the Stripe extension ...

Utilizing angularjs ng-repeat directive to present JSON data in an HTML table

I've been struggling to showcase the JSON data in my HTML table using AngularJS ng-repeat directive. Here's the code snippet: <thead> <tr> <th ng-repeat="(header, value) in gridheader">{{value}}</th> </tr> </ ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...

Moving the inline script in a Next.js custom document is the next step to optimize your code

As a beginner in next.js, I've been focused on enhancing my app's performance. One task I need to tackle is moving the dynamic js files generated by Next.js from the head section to the body tag. I attempted removing NextScript from _document.js ...