简体   繁体   中英

Set State Using getInitialProps of Nextjs for firebase DB

Am trying to build Nextjs app . Am using GetInitialProps to do the SSR through Firebase functions . In getInitialProps , i try to do a database.ref().child and pass the value to the UI .

How can i set the changed value in a state variable so that anytime the value in DB is changed , it reflects in UI .

Currently am returning the value in getInitialProps , and it doesn't reflect when there is a change in DB value . The changed value gets printed on server though when i put a console logger .

CODE :

static async getInitialProps({ req,query }) {

    var customer;

    database.ref().child('someKey').child)
    .on('value', function(snapshot) {
        console.log(snapshot.val());
        customer = snapshot.val();
        console.log(customer.name);
        this.setState({waitNum : customer.waitNum});
        return {customer};
    });

    console.log("Hi Here");
    return {customer};
}

The getInitialProps is only executed once , either server-side (when you first load a page of the website), or client-side (when you navigate to another page using a Link ).

Here are the changes you should do:

  1. Replace the .on('value', ..) by a .once('value', ..) in the getInitialProps .
  2. Add a .on('value', ..) in componentDidMount , so that your component stay updated
  3. Add a off() in componentWillUnmount to stop listening when the component unmount.

Edit:

getInitialProps initialises the props , whereas in componentDidMount the state will be set. This can be addressed by adding a constructor that will initialise the state from the props, and then you can only read the state from the render.

This is usually considered bad practice , because there is now more than one source of truth and it's not clear what to do when both state and props change, but in that particular case I think it is fine because getInitialProps will only run once and if the page change the component will be unmounted.

An alternative is to skip getInitialProps entirely, especially if the only reason to keep it is to reduce the time of first meaningful display, as it's probably not noticeable by the end user. It is usually not worth to do a micro-optimisation that add complexity to the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM