How to display Snack Bar Material UI inside if statment
I want to show a snackbar notification in case my Camera Component returns some error. I tried to put the component inside a function and pass the error message as props, and call it in the if statement but didn't work. I also tried return the snackbar itself, also didn't show up, while, console.log or alert message works fine in both ways. I'm not displaying some part of the code, because it's private, I'm only showing the part about the snackbar. Anyway, if just put some console.log or alert inside the snackBar function, it returns it fine. The problem is with the snackbar. Here is my code:
import React from 'react'
import Snackbar from '@mui/material/Snackbar'
const Camera = () => {
const [open, setOpen] = useState(false)
const snackBar = (errorMessage) => {
setOpen(true)
return <Snackbar open={open} message={errorMessage} />
}
let callback = {
error: function (error) {
console.log(error)
if (error.code === 100) {
return snackBar('error occured')
}
} else if (error.code === 104) {
console.log('104')
return snackBar('Please don't move the phone')
} else if (error.code === 105) {
console.log('105')
setOpen(true)
return snackBar('Try again')}
},
}
return (
<div>
<h1>Camera</h1>
</div>
)
}
export default Camera
You're not calling callback nor snackBar anywhere and you're not returning either in any JSX. You also forgot to import useState
.
If your intent is to provide a callback to handle an error (for example upon fetch), and then display the snackbar, here is an example of how to do it with a (very crude pseudo-code) callback sample
import { Snackbar } from "@mui/material"
import { useState } from "react"
const Camera = () => {
const [errorMessage, setErrorMessage] = useState(null)
const callback = (error) => {
if(error.code === '100') {
setErrorMessage('Message 100')
} else if(error.code === '105') {
setErrorMessage('Message 105')
} // ... add all your other else-ifs here
}
return (
<div>
<h1>camera</h1>
{errorMessage && <Snackbar open={errorMessage} message={errorMessage} />}
</div>
)
}