3

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

wangdev87
  • 8,611
  • 3
  • 8
  • 31
Dika
  • 2,213
  • 4
  • 33
  • 49

1 Answers1

3

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]);
wangdev87
  • 8,611
  • 3
  • 8
  • 31
  • 1
    thanks! as a newbie, I was still confused with your answer but after I try, may I add: this useEffect should be placed inside the react functional component. Outside any normal function. – Dika Dec 11 '20 at 12:07
  • 1
    yes, that' right. for more details, refer to the doc. https://reactjs.org/docs/hooks-effect.html – wangdev87 Dec 11 '20 at 13:15