Manolis P.
Manolis P.

Reputation: 325

React: request to API trigger two times the then block, the request is sended twice

I know that the API call must be not placed into render method, but this is just for testing: I have the below code. When i call the fetchData into the render method the 'Send request ...' message is printed once and the respnse printed twice!?

Output:

Page 1 ... rendering

Send request ...

{data: "Hello there", status: 200, statusText: "", headers: {…}, config: {…}, …}

{data: "Hello there", status: 200, statusText: "", headers: {…}, config: {…}, …}


Why this happens? I have checked also the network tab, and both the request is GET and not a OPTIONS related to CORS.

Also on the server the GET method handler has executed twice.

import React from 'react';
const axios = require('axios').default;

class Page1 extends React.Component {

    // componentDidMount() {
    //     this.fetchData()
    // }

    fetchData() {
        console.log('Send request ...');
        axios.get('http://localhost:8080/api/hello/')
        .then(function (response) {
            console.log(response);
            return response.data;
        })
        .catch(function (error) {
            console.log(error);
        });
    }


    render() {
        console.log('[Page 1] render called')
        this.fetchData();
        return (<h1>Hello from Page 1. </h1>);
    }
}
export default Page1;

Upvotes: 4

Views: 8686

Answers (1)

Keith Brewster
Keith Brewster

Reputation: 3652

When your application is wrapped in <React.StrictMode> your components will render twice in development environments. This is for error/warning detection. Strict mode will intentionally invoke the following class component functions twice: constructors, the render method, and the shouldComponentUpdate methods. Read more about strict mode in the docs.

Upvotes: 16

Related Questions