I have a component that creates a dropdown where the values are a list of policy areas that are pulled from a SQL server database/tables. The selected policy area is then saved into a useState called selectedPolicyArea. I then have a second component that I want to display the stakeholder who is in charge of the policy area, where whenever the selected policy area is changed the stakeholder name will change with it. For example: if Policy Area 1 is selected I expect the stakeholder name John Doe to be the only thing in the stakeholder box, but then if Policy Area 8 is selected then I would expect the stakeholder should switch to Jane Doe.
Dropdown Component and Current Stakeholder component
Here is the code for my Dropdown Component (I did raiase the state up to the parent component so I can use props as this selected value is used in another component as well)
import React, { useState, useEffect } from 'react';
const DropdownGetPolicyArea = (props) => {
const [policyAreaName, setPolicyAreaName] = useState([]);
const [selectedPolicyArea, setSelectedPolicyArea] = useState('');
useEffect(() => {
fetch('/GetPolicyAreaName', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => res.json())
.then(data => setPolicyAreaName(data))
.catch(error => console.error('Error fetching data: ', error));
}, []);
const handleChange = (event) => {
setSelectedPolicyArea(event.target.value);
props.setSelectedPolicyArea(event.target.value)
};
console.log(selectedPolicyArea)
return (
<div className='DropdownGetPolicyArea'>
<h2>Policy Area Name</h2>
<select value={selectedPolicyArea} onChange={handleChange}>
<option value=''>...</option>
{policyAreaName.map((category) => (
<option key={category.Policy_Area_ID} value={category.Policy_Area_Name}>
{category.Policy_Area_Name}
</option>
))}
</select>
</div>
);
};
export default DropdownGetPolicyArea;
Here is the code for my currentPolicyStakeholder component
import React, { useEffect, useState } from 'react';
const CurrentPolicyStakeholder = (props) => {
const [stakeholder, setStakeholder] = useState([]);
useEffect(() => {
const fetchStakeholder = async () => {
try {
const response = await fetch('/GetStakeholder');
const data = await response.json();
setStakeholder(data);
} catch (error) {
console.error('Error fetching stakeholder:', error);
}
};
fetchStakeholder();
}, []);
console.log(stakeholder);
return(
<div>
<ul>{stakeholder.Employee_Preferred_Full_Name}{props.selectedPolicyArea}</ul>
{stakeholder.map((stakeholders) => (
<option>
{stakeholders.Stake_Table_PrimaryKey_ID}
--
{stakeholders.Employee_Preferred_Full_Name}
--
{stakeholders.Employee_ID}
</option>
))}
</div>
);
}
export default CurrentPolicyStakeholder;
My 2 APIs are:
app.get('/GetPolicyAreaName', async(req,res) =>{
console.log('policy area called');
const policyAreaName = await dbOperations.getPolicyAreaName()
res.send(policyAreaName.recordset)
console.log('called');
})
app.get('/GetStakeholder', async(req,res) =>{
console.log('stakeholder called');
const stakeholderName = await dbOperations.getCurrentActivePolicyStakeholder()
res.send(stakeholderName.recordset)
console.log('called');
})
The 2 queries where the data is being pulled from:
const getPolicyAreaName = async(policyAreaName) => {
try {
let pool = await sql.connect(config);
let policyAreaName = await pool.request().query(`SELECT Policy_Area_ID,Policy_Area_Name from Policy_Area`)
return policyAreaName;
}
catch(error) {
console.log(error);
}
}
const getCurrentActivePolicyStakeholder = async() => {
try {
let pool = await sql.connect(config);
let stakeholderName = await pool.request()
.query(`SELECT S.[Stakeholder_ID]
,S.[Employee_ID]
,S.[Employee_Preferred_Full_Name]
,S.[Stakeholder_Role_ID]
,S.[Stake_Table_Name]
,S.[Stake_Table_PrimaryKey_ColName]
,S.[Stake_Table_PrimaryKey_ID]
,PA.Policy_Area_Name
FROM [LegoTest].[dbo].[Stakeholder] S
join [LegoTest].[dbo].[Policy_Area] PA ON PA.Policy_Area_ID = S.Stake_Table_PrimaryKey_ID
WHERE S.Stake_Table_Name = 'Policy_Area'`
)
return stakeholderName;
}
catch(error) {
console.log(error);
}
}
I attempted to do some conditional rendering with if/else and also the ternary operator but could only ever get it to return the entire list of names from the stakeholder table from the database. I had thought that I could potentially use template literals in the getCurrentActivePolicyStakeholder SQL query under the ‘WHERE’ clause but I was unsuccessful at implementing that.
Any and all help/advice is greatly appreciated!
2
Answers
I think to achieve the desired functionality of displaying the stakeholder name dynamically based on the selected policy area, you will need to make a few adjustments to your code.
Try this.
Modify the Backend Endpoint: Update the
/GetStakeholder
endpoint to accept a query parameter for thePolicy_Area_Name
orPolicy_Area_ID
and use it in your SQL query to fetch the relevant stakeholder.Adjust the Frontend to Pass the Selected Policy Area: Modify the fetch call in your
CurrentPolicyStakeholder
component to include the selected policy area as a parameter in the API call.Update Rendering Logic: Modify the rendering logic in the
CurrentPolicyStakeholder
component to correctly display the fetched stakeholder information based on the selected policy area.1. Backend Endpoint Modification
Update your endpoint to accept a parameter and use it in your SQL query:
2. Frontend Modification
Update your
CurrentPolicyStakeholder
component to fetch data based on the selected policy area:3. Update Rendering Logic
Now, update your rendering logic to display the stakeholder. If you only expect one stakeholder per policy area, you can simplify the rendering:
This setup assumes that each policy area will have only one stakeholder. If multiple stakeholders can be associated with a single policy area, you might want to adjust the rendering logic to handle an array of stakeholders.
I hope to help for you.
The list of displayed stakeholders is fetched and held in
CurrentPolicyStakeholder
. You already pass the polciy to this component as props:props.selectedPolicyArea
. What you need to do is to somehow filter the list of stakeholders depending on what’s inprops.selectedPolicyArea
. I’m not sure how’s that supposed to work so I’ll leave the details to you. Here’s how it would look like in general:I changed the name
stakeholder
->stakeholders
becaujse it’s a list. I also added a key to the<option>
tags since they are created in a map (a requirement by React). Why there is an<option>
when there seems to be no<select>
outside of it is unclear, but I left it as it was. Callingin
(previously
<ul>{stakeholder.Employee_Preferred_Full_Name}{props.selectedPolicyArea}</ul>
) also looks wrong because you are trying to access a field of a list. It’sundefined
and this is why it’s not displayed on your screenshot.An additional, off-topic advice:
Doubling the state like this is unnecessary and may cause unexpected behaviour: if you change the state in the parent component from somewhere else other than
DropdownGetPolicyArea
it won’t be transferred to thevalue
of<select>
inDropdownGetPolicyArea
. You should pass the state from the parent component along with the setter:and then use it in the
select
: