0

I am trying to write an HOC with MaterialUI's Snackbar to be able to show error in any network failure. Getting below error, can someone please help:

react-dom.development.js:14724 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
import React from 'react'
import Snackbar from '@material-ui/core/Snackbar'

const SnackbarContext = React.createContext(null)

const withSnackbar = (OriginalComponent) => {
  function componentWithSnackbarContext() {
    const [state, setState] = React.useState({
      open: false,
      message: 'Some network error occurred',
    })

    const { open, message } = state

    const handleNetworkFail = (messageText) => () => {
      setState({ open: true, message: messageText })
    }

    const handleClose = () => {
      setState({ ...state, open: false })
    }

    return (
      <>
        <SnackbarContext.Provider value={{ handleNetworkFail, handleClose }}>
          <OriginalComponent />
        </SnackbarContext.Provider>
        <Snackbar
          anchorOrigin={{ vertical: 'top', horizontal: 'center' }}
          open={open}
          onClose={handleClose}
          message={message}
        />
      </>
    )
  }
  return componentWithSnackbarContext
}

export default withSnackbar
norbitrial
  • 14,716
  • 7
  • 32
  • 59
Deepak Negi
  • 214
  • 4
  • 11

1 Answers1

0

The lint rule assumes that functions starting with capital letters are components, and ones with lower case letters are not. The fix is to change componentWithSnackbarContext to ComponentWithSnackbarContext

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98