Home > Net >  How to Use componentDidMount() in Functional Component to execute a function
How to Use componentDidMount() in Functional Component to execute a function

Time:04-01

I have a functional component which had a button to call a method in it. Now i want to get rid of the button and call that method without any actions once the component loads. I am making API calls inside this method and passing on the results to another component. Also I am replacing the button with a progress bar meaning when a "search" is taking place, display the progress bar but I am having no luck. What am I doing wrong ?

export const Search = (props) => {

    const { contacts, setContacts, onSearchComplete } = props;

    const [msgBox, setMsgBox] = useState(null);
    const [loading, setLoading] = useState(false);

    const onSearch = async () => {

        setLoading(true);

        const emails = contacts
            .filter(x => x.isChecked)
            .map(item => item.emailAddress);

        try {
            const searchResults = await AppApi.searchMany(emails);

            let userList = [];
            for (let i = 0; i < searchResults.length; i  ) {
               //process the list and filter
                }
                userList = [...userList, ..._users];
            }

            onSearchComplete(userList); //passing the results. 
        } catch (err) {
            console.log({ err });
            setMsgBox({ message: `${err.message}`, type: 'error' });
        }

        setLoading(false);
    }


    return (
        <Box>
        
            {loading ? <LinearProgress /> : <Box>{msgBox && (<a style={{ cursor: 'pointer' }} onClick={() => setMsgBox(null)} title="Click  to dismiss"><MessageBox type={msgBox.type || 'info'}>{msgBox.message}</MessageBox></a>)}</Box>}

            /*{onSearch()}*/ // function that was executed onclick. 

        </Box>
    );
}

CodePudding user response:

You will want to use the useEffect hook with an empty dependency array which will make it act as componentDidMount source.


export const Search = (props) => {

    const { contacts, setContacts, onSearchComplete } = props;

    const [msgBox, setMsgBox] = useState(null);
    const [loading, setLoading] = useState(false);

    const onSearch = async () => {
      ...
    }

    useEffect(() => {
      onSearch();
    }, []);


    return (
        <Box>      
            {loading ? <LinearProgress /> : <Box>{msgBox && (<a style={{ cursor: 'pointer' }} onClick={() => setMsgBox(null)} title="Click  to dismiss"><MessageBox type={msgBox.type || 'info'}>{msgBox.message}</MessageBox></a>)}</Box>}
        </Box>
    );
}
  • Related