useState function is not working in functional component

Viewed 767

I want to change a state (filterConsultantId) with a useState function (setFilterConsultantId) after I trigger a normal function (handleConsultantChange) and I expect the state value is changed when I use the state in another normal function (getActiveLeads). But the state didn't change. Please see my React functional component below:

const TabActiveLeads = ({
    ...
}) => {
    const [filterConsultantId, setFilterConsultantId] = useState('');   
    
    //after this arrow function triggered, 
    const handleConsultantChange = (event) => {
        setFilterConsultantId(event.target.value); //and the filterConsultantId should be changed here
        
        //this getActiveLeads function is called
        getActiveLeads();
    };
    
    const getActiveLeads = () => {
        
        // but the filterConsultantId here is not changed after it should be changed inside handleConsultantChange function
        console.log(filterConsultantId);
    }; 
};

export default TabActiveLeads;

I don't understand, why filterConsultantId is not changed inside the getActiveLeads function? Previously it should be changed by calling setFilterConsultantId inside the handleConsultantChange function.

Thanks for any help..

1 Answers

setFilterConsultantId is the asynchronous method, so you can't get the updated value of filterConsultantId right after setFilterConsultantId. You should get it inside useEffect with adding a dependency filterConsultantId.

useEffect(() => {
  console.log(filterConsultantId);
}, [filterConsultantId]);
Related