N
N
nano_e_t_42021-11-29 17:13:09
Frontend
nano_e_t_4, 2021-11-29 17:13:09

Why does this.props.Func return undefined?

Hello everyone
, I have a function that makes a post request and, in theory, should return a status code in the response

someAwesomeFunction= (arg1) => {
        let data = JSON.stringify({
            "arg1": arg1,
        })
        // Send a POST request
        axios({
            method: 'post',
            url: awesomeUrl,
            data: data,
            headers: {
                "Content-Type": "application/json"
            }
        }).then((response) => {
            console.log(response.status)       ##вот здесь печатает статус код
            return (response.status)
        })
            .catch((error) => {
                console.log(error)
                return 500
            })}


this function is "imported" from the context to use it in different components

when I call it from the component, it works fine and the server does its part of the work,

but when I try to read the response, I get undefined

handleClick = () => {
        let response = this.props.someAwesomeFunction(this.props.arg)
        console.log(response)           ######вот здесь получаю undefined
    }
    render() {
        return <button
            className={this.props.isActive ? 'active' : 'album'}
            onClick={this.handleClick} > {this.props.someAwesomeArg}
        </button>
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Osher, 2021-11-29
@nano_e_t_4

Add a return statement before calling axios.

someAwesomeFunction= (arg1) => {
        let data = JSON.stringify({
            "arg1": arg1,
        })
        // Send a POST request
        return axios({
            method: 'post',
            url: awesomeUrl,
            data: data,
            headers: {
                "Content-Type": "application/json"
            }
        }).then((response) => {
            console.log(response.status)       ##вот здесь печатает статус код
            return (response.status)
        })
            .catch((error) => {
                console.log(error)
                return 500
            })}

Then wait for the asynchronous operation
// вариант 1
handleClick = async () => {
        let response = await this.props.someAwesomeFunction(this.props.arg)
        console.log(response)           ######вот здесь получаю undefined
    }

// вариант 2
handleClick = () => {
        this.props.someAwesomeFunction(this.props.arg).then(response => {
             console.log(response);
        });
    }

In general, I advise you to carefully read and understand https://learn.javascript.ru/async

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question