skip to Main Content

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

What console looks like when value is selected from dropdown and what the data looks like being pulled in from the 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


  1. 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.

    1. Modify the Backend Endpoint: Update the /GetStakeholder endpoint to accept a query parameter for the Policy_Area_Name or Policy_Area_ID and use it in your SQL query to fetch the relevant stakeholder.

    2. 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.

    3. 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:

    app.get('/GetStakeholder', async(req, res) => {
        const { policyAreaId } = req.query; // assuming the front end sends policyAreaId
        try {
            let pool = await sql.connect(config);
            let stakeholderName = await pool.request()
                .input('policyAreaId', sql.Int, policyAreaId)
                .query(`SELECT S.[Employee_Preferred_Full_Name]
                        FROM [dbo].[Stakeholder] S
                        JOIN [dbo].[Policy_Area] PA ON PA.Policy_Area_ID = S.Stake_Table_PrimaryKey_ID
                        WHERE PA.Policy_Area_ID = @policyAreaId AND S.Stake_Table_Name = 'Policy_Area'`);
            res.json(stakeholderName.recordset);
        } catch (error) {
            console.error('Error fetching stakeholder:', error);
            res.status(500).send('Server error');
        }
    });
    

    2. Frontend Modification

    Update your CurrentPolicyStakeholder component to fetch data based on the selected policy area:

    useEffect(() => {
        if (props.selectedPolicyArea) { // Ensure there is a selected policy area
            const fetchStakeholder = async () => {
                try {
                    const response = await fetch(`/GetStakeholder?policyAreaId=${encodeURIComponent(props.selectedPolicyArea)}`);
                    const data = await response.json();
                    setStakeholder(data);
                } catch (error) {
                    console.error('Error fetching stakeholder:', error);
                }
            };
            fetchStakeholder();
        }
    }, [props.selectedPolicyArea]); // Dependency array ensures useEffect runs when selectedPolicyArea changes
    

    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:

    return (
        <div>
            {stakeholder.length > 0 && (
                <div>
                    <h3>Stakeholder for {props.selectedPolicyArea}:</h3>
                    <p>{stakeholder[0].Employee_Preferred_Full_Name}</p>
                </div>
            )}
        </div>
    );
    

    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.

    Login or Signup to reply.
  2. 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 in props.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:

    import React, { useEffect, useState } from 'react';
    
    const CurrentPolicyStakeholder = (props) => {
      const [stakeholders, setStakeholders] = useState([]);
      
      const filteredStakeholders = React.useMemo(() => {
        
        function filterPredicate(stakeholder) {
          //return true if this stakeholder is supposed to be displayed for given policy area, 
          // return false otherwise
          // for example
          return stakeholder.policyArea === props.selectedPolicyArea;
        }
        
        return stakeholders.filter(filterPredicate);
      }, [props.selectedPolicyArea, stakeholders]);
    
      useEffect(() => {
        const fetchStakeholder = async () => {
          try {
            const response = await fetch('/GetStakeholder');
            const data = await response.json();
            setStakeholders(data);
          } catch (error) {
            console.error('Error fetching stakeholders:', error);
          }
        };
        fetchStakeholder();
      }, []);
    
      console.log(stakeholders);
    
      return(
        <div>
          <ul>{stakeholders.Employee_Preferred_Full_Name}{props.selectedPolicyArea}</ul>
    
          {filteredStakeholders.map((stakeholder) => (
            <option key={stakeholder.Employee_ID}>
              {stakeholder.Stake_Table_PrimaryKey_ID}
              --
              {stakeholder.Employee_Preferred_Full_Name}
              --
              {stakeholder.Employee_ID}
            </option>
    
          ))}
        </div>
      );
    
    }
    
    
    export default CurrentPolicyStakeholder;
    

    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. Calling

    stakeholders.Employee_Preferred_Full_Name
    

    in

    <ul>{stakeholders.Employee_Preferred_Full_Name}{props.selectedPolicyArea}</ul>
    

    (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’s undefined and this is why it’s not displayed on your screenshot.

    An additional, off-topic advice:

     const handleChange = (event) => {
        setSelectedPolicyArea(event.target.value);
        props.setSelectedPolicyArea(event.target.value)
     };
    

    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 the value of <select> in DropdownGetPolicyArea. You should pass the state from the parent component along with the setter:

     const handleChange = (event) => {
        props.setSelectedPolicyArea(event.target.value)
     };
    

    and then use it in the select:

    <select  value={props.selectedPolicyArea} onChange={handleChange}>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search