D
D
danil_linkins2018-04-03 11:42:51
React
danil_linkins, 2018-04-03 11:42:51

React - How to properly build work with an external api?

I have a main "App" component class which I render in reactDOM.render.
There I have a form in which the submit handler is specified:

<UI.FormLayout onSubmit={this.handleSubmit} v="new" allowSubmit={true} style={{ padding: "0", paddingBottom: "65px" }}>
                            <GetTest />
                            <UI.Group title="Отправление результатов">
                                <UI.List>
                                    <UI.ListItem>
                                        <UI.Input v="new" type="text" placeholder="Your name" label="Ваше имя" required />
                                    </UI.ListItem>
                                    <UI.ListItem>
                                        <UI.Input v="new" type="tel" placeholder="Phone" label="Ваш телефон" required />
                                    </UI.ListItem>
                                    <UI.ListItem>
                                        <UI.Input v="new" type="email" placeholder="E-mail" label="Ваш e-mail" required />
                                    </UI.ListItem>
                                    <UI.ListItem>
                                        <UI.Button appearance="vk-rich" type="submit" value="Submit">Завершить тест</UI.Button>
                                    </UI.ListItem>
                                </UI.List>
                            </UI.Group>
                        </UI.FormLayout>

(Ignore the UI and components, just a library). (GetTest - getting form data via API).
And there is the function itself where I make a request to some file on the server:
handleSubmit (event){
        event.preventDefault();

        console.log("submit complete");

        fetch("//some_url.com/api", {
            method: "POST",
            headers: {
                "Content-type": "application/json"
            },
            mode: "no-cors",
            credentials: "include",
            body: "response.formData()"
        })
            .then(result => result.json())
            .then(
                (result) => {
                    this.setState({
                        isLoaded: true,
                        TestResults: result,
                        activePanel: 'Results'
                    });
                },
                (error) => {
                    this.setState({
                        isLoaded: true,
                        error,
                        activePanel: 'Error'
                    });
                }
            );
    }

But here’s what I don’t understand, if I sent the data, the script on the server processed it and answered with some data.json, then how can I then take this data, process it and display it?
I tried to make a separate class for this case, which was called in the main App and would be shown if the data was successfully received, but in the class itself I create an empty array in the state that does not contain the data received from the server and it’s not at all clear how it I have it connected with the submit processing function. The code:
class PrintResult extends  Component {
    constructor(props) {
        super(props);
        this.state = {
            error: null,
            isLoaded: false,
            TestResults: []
        };
    }

    render() {
        const { error, isLoaded, TestResults } = this.state;
        if (error) {
            return <div>Error: {error.message}</div>;
        } else if (!isLoaded) {
            return (
                <UI.View popout={<UI.ScreenSpinner />} activePanel="spinner" header>
                    <UI.ScrollView header={{ title: 'Screen Spinner' }} id="spinner">

                    </UI.ScrollView>
                </UI.View>
            );
        } else {
            return (
                <UI.Div style={{ padding: '4px 0' }}>
                    {TestResults.map((item) => (
                        <UI.Div>
                            {item}
                        </UI.Div>
                    ))}
                </UI.Div>
            );
        }
    }
}

And the result is a constant loading state (!isLoaded) or the page is simply updated.
The question is, how do you tie it all together? So that the submit handler sends data, receives data and immediately displays them in the right place? Please tell me what you know. Any advice is appreciated.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-04-03
@danil_linkins

It's not clear from the question where the problem is.
You load the data asynchronously in the component where you need it at the moment of componentDidMount, then write it to the state (using this.setState) and react itself will call the render function => your data will appear on the screen.
> In order for the submit handler to send data
to make a request
> receive data and immediately display them in the right place
put in state. If the "right place" is another component, then you need to keep the state in the parent and update it using the function passed as props to the component where the data is called. And the other component, where the data is needed, simply receives it from the state of the parent component as props and renders in the same way (if new props arrive, the react also calls render)
Key point: if your components do not know anything about each other, then you need to put the data "on top" in a common parent.
ps In my opinion, you are starting to parse everything correctly, the main thing to remember is that you can pass a function (callback) from the parent as props, and through it you can set the data to the parent's state, etc. etc.
pps, you usually don't have to do this, because either the data lives in the right component beforehand, or you are already using redux or something similar.

// Parent component
...
state = {
  data: [],
}
...
myMethodInParent = (values) => {
  this.setState({data: values })
}
...
render() {
 ...
 <AnyChildren testName={this.myMethodInParent} />
}

// AnyChildren component
...

handleSubmit() => {
  this.props.testName( _ваши_данные_которые_нужно_в_стейт_родителя_ )
}
...
render() {
...
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question