Next.js: Can't use componentDidMount() hooks withAmp()

Created on 9 Jun 2019  路  2Comments  路  Source: vercel/next.js

Bug report

Describe the bug

Can't use componentDidMount() hooks on components inside pages which use withAmp().
I tried to use IntersectionObserver to create lazy load image. Everything is fine until I export with withAmp(), ComponentDidMount() hooks seems not to be working, I tried console.log() inside componentDidMount hooks, no luck.

To Reproduce

Steps to reproduce this behavior

  1. Set up a Next.js project: as same as code on above
  2. Add these code to the set up

pages/index.js

import React, { Fragment } from 'react'
import { withAmp } from 'next/amp'
import Card from '../components/card'

const App = () => (
    <Fragment>
        <h1>Hello World</h1>
        <Card />
    </Fragment>
)

export default withAmp(App)

components/card.js

import React, { useEffect } from 'react'

const Card = () => {
    useEffect(() => {
        console.log("Start Observe!")
    }, [])

    return(
        <div>
            <h1>Card</h1>
        </div>
    )
}

export default Card
  1. Start dev server
  2. Check on browser and see no log "Start Observe!"
  3. Try export without withAmp() and check on browser again (Hard refresh), you'll see "Start Observe!"

Expected behavior

withAmp() does messed up ComponentDidMount() for some reason, hope there's a why to resolve this issue.
What I expected to see is: To use componentDidMount or other relate way to be able to set state after served on client side and is rendered.

Screenshots

Without withAmp()
image

With withAmp()
image

System information

  • OS: Windows 10
  • Tried on Chrome and Firefox.
  • Next.js 8.1.0, react: 16.8.6, react-dom: 16.8.6
  • Node 12.3.1, yarn 1.15.2

Additional context

Is there a relevant way to run function after served on client side and rendered but still can be able to use set state?

Most helpful comment

There is no Next.js or React client-side runtime in AMP-only mode https://github.com/zeit/next.js#amp-page-modes use the Hybrid one instead.

All 2 comments

There is no Next.js or React client-side runtime in AMP-only mode https://github.com/zeit/next.js#amp-page-modes use the Hybrid one instead.

Thanks @MarchWorks.

Probably good to note that if your app only has client-side JS for image lazy loading you probably want to use AMP First with amp-img which does lazy loading by default.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sospedra picture sospedra  路  3Comments

wagerfield picture wagerfield  路  3Comments

irrigator picture irrigator  路  3Comments

swrdfish picture swrdfish  路  3Comments

jesselee34 picture jesselee34  路  3Comments