Utilize SWR to retrieve data that corresponds to the chosen value from the dropdown menu

Can SWR fetch data based on the selected value in a dropdown? Initially, it works, but when I select a previously selected value, it doesn't fetch the correct data.

  1. Using the Fetch API
   const { data: entities } = useSWR(
       currentEntity?.entity_id
         ? "/api/entities/" + currentEntity?.entity_id
         : null,
       { dedupingInterval: 12000 }
     );
  1. This is how the data is rendered when returned
     {!isEmptyObject(individual) &&
                  isTabThree &&
                  selectedEntity === "" ? (
                    <div className="flex items-center justify-center h-48 text-gray-500">
                      Please choose an entity
                    </div>
                  ) : !entities ? (
                    <div className="flex items-center justify-center h-48">
                      <ThreeDotsSpinner />
                    </div>
                  ) : (
                    <EntityForm data={entities} />
                  )}
  1. This is the entity form where data will be stored in input. The desired behavior is that whenever the dropdown changes, the form also changes to display the correct data through the fetch API.
    export default function EntityForm({ data }) {
    
      
      const formik = useFormik({
        initialValues: {
          // Form field initial values here
        },
      });
      return (
        // Form structure and fields here
      );
    }
  1. This is the dropdown component from headlessui that has recently been utilized
import { Fragment, useState } from "react";
// Code for the ListBox component goes here
  1. This is the API call for the current customer, including all data, such as entities. The id is obtained through the router query, and the currentEntity is derived from the selected entity.
const { data: customer } = useSWR(
        id
          ? "/api/customer/" + id
          : null
      );
  1. Explanation of how the currentEntity is retrieved. The selectedEntity is a state where the chosen entity from the dropdown is stored.
const currentEntity = customer?.summary?.type_entities?.find((val) => val.entity_name === selectedEntity)

If you have any questions or need further clarification on any of the above, feel free to ask. Your assistance and guidance are sincerely appreciated as I navigate through these concepts as a newcomer. Thank you for your support and understanding.

Answer №1

The issue has been resolved, although I am unsure if it is the optimal solution. I integrated my Formik form with enableReinitialize to automatically update the initial values whenever the dropdown value is modified.

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

The active tabs or placeholders do not update properly when I click on them

Is there anyone who can help figure out why the tabs are not functioning as expected? The goal is for the tabs to change the input field placeholder and perform a search based on the active tab. If you're able to assist, please review my complete cod ...

Exploring JavaScript Unit Testing: Essential dependencies for testing with Karma, jasmine, and bootstrap

After creating an application using AngularJS and additional tools based on bootstrap, I am now facing the challenge of testing everything. However, there seems to be a problem with Karma and Jasmine as an exception is thrown when running the tests. The i ...

Having trouble with either posting a JSON using $.ajax() or reading it using PHP?

I'm struggling to identify the issue at hand. Here's my JavaScript function for sending JSON data: function send(var1, var2) { var result; att = window.location; $.ajax({ 'crossDomain': true, 'type&apos ...

Invalid component prop provided to ButtonBase in Material UI. Ensure that the children prop is correctly rendered in this custom component

Forgive me for asking a basic question, as I am not the most proficient frontend developer and have searched extensively online. Whenever I inspect my frontend application in Chrome, I keep encountering this error. (3) Material-UI: The component prop pro ...

JavaScript Ping Pong Challenge

I'm currently investigating why the browser returns NaN for the Positions. The game is being rendered in a loop and updated as soon as the monitor is ready, which is defined in the update() function and runs infinitely. The reset() function is a part ...

Encountering an issue: ReferenceError: regeneratorRuntime is not defined when implementing react-speech-recognition in nextjs13

Encountering the errorReferenceError: regeneratorRuntime is not defined in my NextJS project I'm currently using Redux toolkit. Link to my project. Please note that the code triggering the error can be found under the nextjsfrontend branch. I' ...

Tips for utilizing Vue.js techniques to assign values to data properties

As a newcomer to Vue.js, I am in the process of learning how to display data retrieved from a server. In my new Vue app, I have defined a method: methods: { getData: function() { // making a request, parsing the response and pushing it to the array. ...

Issues with Vue Router functionality in Leaflet Popup are causing unexpected behavior

Incorporating Leaflet and Vue together in my codebase using the vue2-leaflet wrapper has presented a challenge. Specifically, I am facing difficulties getting Vue $router to function within Leaflet's popup. Below is a snippet of my current code along ...

Utilizing an Immediate-Invoked Function Expression (IIFE) for jQuery in JavaScript

I'm looking at this code snippet that I believe is an Immediately Invoked Function Expression (IIFE). But, I'm confused about the role of (jQuery) and ($). I understand that it involves passing a reference to jQuery into the IIFE, but can someone ...

Is there a way to improve efficiency in JavaScript and JSON by reducing the size of the array?

My partner and I are currently collaborating on the development of a small web application. This app serves as an information hub, sourcing data from a JSON file that is expected to contain around 150 items, each with approximately 130 properties. As we c ...

Incorporating a background image into a card component using props

I attempted to add a background image to the card component through props, but the image failed to display on the card. I didn't encounter any errors, and I'm unsure what mistake I might be making. Any suggestions or alternative solutions would b ...

Tips for improving the scrolling function in Java with Selenium for optimal performance

I'm currently working on a project using Java in MAVEN. My task involves retrieving a URL, scrolling down the page, and extracting all the links to other items on that website. So far, I have been able to achieve this dynamically using Selenium, but ...

How can I create an efficient chat system using Ajax and settimeout without causing excessive virtual memory usage?

I'm in the process of creating a chat application using AJAX that fetches data every second with setTimeout. I have drafted a basic code where there is a number that increments each second by the number retrieved from the PHP page2. Upon testing it on ...

Does angular have a feature comparable to JavaScript's .querySelectorAll()?

I developed an inventory calculator in JavaScript that provides item count based on weight. The calculator has 4 inputs, and now I'm looking to replicate the same functionality using Angular. Is there a method in Angular similar to .querySelectorAll() ...

Can someone show me how to use the IN operator in a PostgreSQL query in an Express.js (Node.js

My Approach to Writing Code var employees=[1,2,3]; await client.query( "SELECT user_id FROM group_user WHERE user_id IN($1)", employees ); An error is thrown indicating that only one parameter needs to be provided ...

Building a Laravel PHP application that dynamically generates a custom JSON object fetched from the database and passes it from PHP to

I am faced with the task of generating a custom JSON object by organizing data retrieved from PHP in my Controller. I have full control over what information goes where and in what specific order. To accomplish this, it seems like I will need to go throug ...

Sophisticated solution for html5 video fallback with JavaScript

My Django website allows users to upload videos in mp4 format for others to watch. However, there are cases where certain browsers cannot play this format, like Firefox. In such scenarios, I want to provide a fallback option to download the video instead o ...

Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements. For example, consider this original array ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

Guide to sending a response to an AJAX post request in Express with Node.js: Answered

For a project focused on practicing Node.js and jQuery Ajax, I'm working on a simple task. Essentially, I have an ajax post request that sends data to a Node.js server and waits for a response. On the server-side, there's code that processes this ...