DEV Community

SteerClear90
SteerClear90

Posted on

How to make http call onclick using stateless component in ReactJS?

I have a React stateless function component (SFC). I want a user to click a button and onclick a http call will be made from the SFC and when the response is received, I want to open a modal. Is it something achievable using SFC? Or do I need to keep a stateful component?

This is my code which makes the http call on load and then onClick opens the modal. But I want both the things to happen in sequence on the onClick event.


function httpListCall(url) {
    const [list, setData] = React.useState(null);
    const [error, setError] = React.useState(null);
    React.useEffect(() => {
        axios
            .get(url)
            .then(function (response) {
                setData(response.data.ResultList);
            })
            .catch(function (error) {
                setError(error);
            })
    }, []);
    return { list, error };
};

Enter fullscreen mode Exit fullscreen mode

const ListContainer = () => {
    const { list, error } = httpListCall("/list.json"); //THIS IS ON LOAD NOW - I WANT TO CALL IT onClick
    const [modalShow, setModalShow] = React.useState(false);

Enter fullscreen mode Exit fullscreen mode
return(
    <React.Fragment>
        <div>
           <button onClick={() => setModalShow(true)}/> //WANT TO MAKE API CALL HERE AND THEN OPEN THE MODAL
        </div>
        <ModalWidget show={modalShow} list={advisorList} error={error} onHide={() => setModalShow(false)}/>
    </React.Fragment>
)
Enter fullscreen mode Exit fullscreen mode

}


export default ListContainer;
ReactDOM.render(<FindAdvisorContainer />, document.getElementById("app"));

Enter fullscreen mode Exit fullscreen mode

I have tried to make the http call from a function but it gives me an error: "Invalid hook call. Hooks can only be called inside of the body of a function component."

Top comments (0)