jimmy
jimmy

Reputation: 1719

How to do server side render using next.js?

When I create a simple app, I found that next.js will automatically do the server side render.

But when I tried to fetch the data from backend, I found that server side won't get the data.

How to fetch the data from server side? So that I can do the server side render?

components/test.js

import React, { Component } from 'react';
class Test extends Component {
    constructor(){
        super();
        this.state={
            'test':''
        }
    }

    setTest(){

        axios.get(serverName+'/api/articles/GET/test').then(response=>{

            let test;
            test = response.data.test;
            this.setState({test});

        }).catch(function (error) {
            console.log(error);
        });
    }
    }

    render() {
        return (
            <div>
                {this.state.test}
            </div>
        );
    }
}
export default Test;

backend is just like following:

function getTest(Request $request){
    return response()->json(['test'=>'this is a test']);
}

Upvotes: 1

Views: 1896

Answers (2)

iurii
iurii

Reputation: 4230

Next.js uses getInitialProps that is executed on the server on initial load only.

From docs

For the initial page load, getInitialProps will execute on the server only. getInitialProps will only be executed on the client when navigating to a different route via the Link component or using the routing APIs.

All other lifecycle methods/actions on React components (componentDidMount, onClick, onChange etc) are executed on the client side.

Example code

class Test extends Component {
  static async getInitialProps() {
    const response = await axios.get(serverName + '/api/articles/GET/test');

    return { test: response.data.test }
  }

  render() {
    return <div>{this.props.test}</div>;
  }
}

export default Test;

Upvotes: 1

Mustkeem K
Mustkeem K

Reputation: 8798

Like below. I would recomend to use getInitialProps. This is recommended approach by next.js to get data at server.

import React from 'react'

export default class extends React.Component {
  static async getInitialProps({ req }) {
  
  axios.get(serverName+'/api/articles/GET/test').then(response=>{
            let test;
            test = response.data.test;
            return { test }
        }).catch(function (error) {
             return { response }
        });  
  }

  render() {
    return (
      <div>
        Hello World {this.props.test.name}
      </div>
    )
  }
}

Upvotes: 0

Related Questions