K
K
kova1ev2019-04-26 22:41:58
JavaScript
kova1ev, 2019-04-26 22:41:58

How to properly move a function with an asynchronous request to a separate module?

Hello, I'm learning React, I just can't understand one thing.
I have a number of components that send asynchronous requests to an api server. I make requests using the fetch function. Receiving a response, they change the state and the component is redrawn. The bottom line is that in all components there is almost the same code for these requests, with the exception of the URL. I wanted to make a function in a separate file that received the URL in the parameters and returned the server response, and then use it in all components, but due to the fact that the request is asynchronous, the function does not work, since the return is executed before the response from the server arrives.
Just in case, I will attach the code of one of the components

class Test extends React.Component {

    state = {
        storages:[]
    }
    
    load_data = () => {
        fetch('/storages')
        .then(response => response.json())
        .then(data => this.setState({
          storages: data
        }));
    }

    render() {
        const storages = this.state.storages.map(function(item, index) {
            return (
                <tr key={index}><td>{item.name}</td><td>{item.adress}</td><td>{item.area}</td></tr>
            )
        });

        return (
            <React.Fragment>
                <button onClick={this.load_data}>Склады</button>
                <table>
                    <tr><th>Название</th><th>Адрес</th><th>Площадь(кв.м)</th></tr>
                    {storages}
                </table>
            </React.Fragment>
        );
    }
}

export default Test;

The load_data() function is repeated in all components. Tell me, plz, how to get rid of duplication?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Rsa97, 2019-04-26
@kova1ev

Pass to your function a callback for redrawing or a selector of the element to be redrawn.

M
Max Medar, 2017-03-24
@MedVedar

What sliders have you tried and what exactly did not work for you? You take slider elements and insert your forms into it or whatever you need. Slick slider for example.

V
Vasya Petrov, 2017-03-24
@VasyaPertrov

The third time I ask a question, but there is no standard answer.

Are you too lazy to search and choose what YOU need:?
Ok here is one of many https://wordpress.org/plugins/smart-slider-3/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question