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.
- Using the Fetch API
const { data: entities } = useSWR(
currentEntity?.entity_id
? "/api/entities/" + currentEntity?.entity_id
: null,
{ dedupingInterval: 12000 }
);
- 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} />
)}
- 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
);
}
- This is the dropdown component from headlessui that has recently been utilized
import { Fragment, useState } from "react";
// Code for the ListBox component goes here
- 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
);
- 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.