Second argument in reactjs function is undefined - javascript

I have been working on a small project to get familiar with ReactJS and am having lots of fun so far. I have had a few issues that have been resolved with help from here so far.
Currently, I am working on changing the links in my header based on the role of an authorized user. That part seems to be working fine, until I try and sign up a user. I am getting an issue where the props.firebase line of code is undefined. Any ideas of what I need to do to make this not undefined? When I remove the {authUser} argument, everything seems to go fine, but problems occur when adding that to the function. The code for the SignUp file is below:
import {Link as RouterLink, withRouter} from 'react-router-dom'
import {compose} from 'recompose';
import {withFirebase} from '../../components/Firebase'
import * as ROUTES from '../../constants/routes'
import Avatar from '#material-ui/core/Avatar';
import Button from '#material-ui/core/Button';
import CssBaseline from '#material-ui/core/CssBaseline';
import TextField from '#material-ui/core/TextField';
import Link from '#material-ui/core/Link';
import Grid from '#material-ui/core/Grid';
import Box from '#material-ui/core/Box';
import LockOutlinedIcon from '#material-ui/icons/LockOutlined';
import Typography from '#material-ui/core/Typography';
import {makeStyles} from '#material-ui/core/styles';
import Container from '#material-ui/core/Container';
import SignInPage, {SignInLink} from "../SignInPage";
import styles from '../../assets/jss/website-template/views/signUpPage';
import Header from '../../components/Header/Header';
import HeaderLinks from '../../components/Header/HeaderLinks';
import image from '../../assets/img/kissing.JPG';
import Paper from '#material-ui/core/Paper';
import AuthUserContext from '../../components/Session/context';
function Copyright() {
return (
<Typography variant="body2" color="textSecondary" align="center">
{'Copyright © '}
<Link color="inherit" href="https://material-ui.com/">
Your Website
</Link>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
);
}
const useStyles = makeStyles(styles);
const SignUpPage = () => (
<div>
<AuthUserContext.Consumer>
{authUser => authUser === null ?
<SignUpForm authUser={null} /> :
<SignUpForm authUser={authUser} /> }
</AuthUserContext.Consumer>
</div>
);
const SignUpFormBase = ({authUser}, props) => {
const classes = useStyles();
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [passwordOne, setPasswordOne] = useState('');
const [passwordTwo, setPasswordTwo] = useState('');
const [inviteCode, setInviteCode] = useState('');
const [error, setError] = useState(null);
const {...rest} = props;
const isInvalid =
passwordOne !== passwordTwo ||
passwordOne === '' ||
email === '' ||
username === '';
const doSubmit = event => {
props.firebase
.checkInviteCode(inviteCode)
.then(role => {
props.firebase
.doCreateUserWithEmailAndPassword(email, passwordOne)
.then(authUser => {
return props.firebase
.user(authUser.user.uid)
.set({
username,
email,
role,
});
})
.then(authUser => {
setUsername(username);
setPasswordOne(passwordOne);
setPasswordTwo(passwordTwo);
setEmail(email);
setInviteCode(inviteCode);
props.history.push(ROUTES.HOME);
})
.catch(error => {
setError(error);
});
})
.catch(error => {
console.log(error);
});
event.preventDefault();
}
return (
<div>
<Header
absolute
color="transparent"
brand="Material Kit React"
rightLinks={<HeaderLinks authUser={authUser}/>}
{...rest}
/>
<div
className={classes.pageHeader}
style={{
backgroundImage: "url(" + image + ")",
backgroundSize: "cover",
backgroundPosition: "top center"
}}
>
<Grid component="main" className={classes.container}>
<CssBaseline/>
<Grid item component={Paper} xs={12} sm={12} md={4}>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon/>
</Avatar>
<Typography component="h1" variant="h5">
Sign up
</Typography>
<form className={classes.form} noValidate onSubmit={doSubmit}>
<TextField
margin="normal"
autoComplete="fname"
name="username"
variant="outlined"
required
fullWidth
id="username"
label="Username"
autoFocus
value={username}
onChange={event => setUsername(event.target.value)}
/>
<TextField
margin="normal"
variant="outlined"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
value={email}
onChange={event => setEmail(event.target.value)}
/>
<TextField
margin="normal"
variant="outlined"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
value={passwordOne}
onChange={event => setPasswordOne(event.target.value)}
/>
<TextField
margin="normal"
variant="outlined"
required
fullWidth
name="password"
label="Confirm Password"
type="password"
id="password"
autoComplete="confirm-password"
value={passwordTwo}
onChange={event => setPasswordTwo(event.target.value)}
/>
<TextField
margin="normal"
variant="outlined"
required
fullWidth
name="inviteCode"
label="InviteCode"
id="inviteCode"
autoComplete="inviteCode"
value={inviteCode}
onChange={event => setInviteCode(event.target.value)}
/>
<Button
type="submit"
fullWidth
variant="contained"
className={classes.submit}
disabled={isInvalid}
>
Sign Up
</Button>
{error && <p>{error.message}</p>}
<Grid container>
<Grid item>
<SignInLink href="#" variant="body2"/>
</Grid>
</Grid>
<Box mt={2}>
<Copyright/>
</Box>
</form>
</div>
</Grid>
</Grid>
</div>
</div>
);
}
const SignUpLink = () => (
<p>
<RouterLink to={ROUTES.SIGN_UP}>Don't have an account? Sign Up</RouterLink>
</p>
);
const SignUpForm = compose(
withFirebase,
withRouter,
)(SignUpFormBase);
export default SignUpPage;
export {SignUpForm, SignUpLink};
As i mentioned, the issue is with the props.firebase being undefined, so it can't find the checkInviteCodes() function.

Props are always the first argument, and the proper signature of a function-based component is Component(props)
Change this one:
const SignUpFormBase = ({authUser}, props) => {
...
to:
const SignUpFormBase = ({authUser, firebase}) => {
...
Or
const SignUpFormBase = (props) => {
...
and refer to authUser and firebase as props.authUser and props.firebase
Your previous solution, that is const SignUpFormBase = ({authUser}, props) => { destructures props and assigns its authUser to a local variable of the same name. The second (and every further) argument is simply undefined.

Related

Having an issue with shipping options

I have a problem fetching the shipping options, the error: 'Unhandled Rejection (TypeError): undefined is not an object (evaluating 'options[0].id')'. I have checked everything I can think of to debug this issue. I am using check.io as for my e-commerce backend. I have added different shipping option on that site however they are not showing up. I have a hard time understanding why there is a type error
import React, { useState, useEffect } from "react";
import {
InputLabel,
Select,
MenuItem,
Button,
Grid,
Typography,
} from "#material-ui/core";
import { useForm, FormProvider } from "react-hook-form";
import { Link } from "react-router-dom";
import FormInput from "../CheckoutForm/CustomTxtField";
import { commerce } from "../../lib/Commerce";
const AddressForm = ({ checkoutToken, test }) => {
const [shippingCountries, setShippingCountries] = useState([]);
const [shippingCountry, setShippingCountry] = useState("");
const [shippingSubdivisions, setShippingSubdivisions] = useState([]);
const [shippingSubdivision, setShippingSubdivision] = useState("");
const [shippingOptions, setShippingOptions] = useState([]);
const [shippingOption, setShippingOption] = useState("");
const methods = useForm();
const fetchShippingCountries = async (checkoutTokenId) => {
const { countries } = await commerce.services.localeListShippingCountries(
checkoutTokenId
);
setShippingCountries(countries);
setShippingCountry(Object.keys(countries)[0]);
};
const fetchSubdivisions = async (countryCode) => {
const { subdivisions } = await commerce.services.localeListSubdivisions(
countryCode
);
setShippingSubdivisions(subdivisions);
setShippingSubdivision(Object.keys(subdivisions)[0]);
};
const fetchShippingOptions = async (
checkoutTokenId,
country,
stateProvince = null
) => {
const options = await commerce.checkout.getShippingOptions(
checkoutTokenId,
{ country, region: stateProvince }
);
setShippingOptions(options);
setShippingOptions(options[0].id);
};
useEffect(() => {
if (checkoutToken && checkoutToken.id) {
fetchShippingCountries(checkoutToken.id);
console.log(checkoutToken.id);
}
}, [checkoutToken]);
useEffect(() => {
if (shippingCountry) fetchSubdivisions(shippingCountry);
}, [shippingCountry]);
useEffect(() => {
if (shippingSubdivision)
fetchShippingOptions(
checkoutToken.id,
shippingCountry,
shippingSubdivision
);
}, [shippingSubdivision]);
return (
<div>
<Typography variant="h6" gutterBottom>
Shipping address
</Typography>
<FormProvider {...methods}>
<form
onSubmit={methods.handleSubmit((data) =>
test({
...data,
shippingCountry,
shippingSubdivision,
shippingOption,
})
)}
>
<Grid container spacing={3}>
<FormInput name="firstName" label="First name" />
<FormInput name="lastName" label="Last name" />
<FormInput name="address1" label="Address line 1" />
<FormInput name="email" label="Email" />
<FormInput name="city" label="City" />
<FormInput name="zip" label="Zip / Postal code" />
<Grid item xs={12} sm={6}>
<InputLabel>Shipping Country</InputLabel>
<Select
value={shippingCountry}
fullWidth
onChange={(e) => setShippingCountry(e.target.value)}
>
{Object.entries(shippingCountries)
.map(([code, name]) => ({ id: code, label: name }))
.map((item) => (
<MenuItem key={item.id} value={item.id}>
{item.label}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>Shipping Subdivision</InputLabel>
<Select
value={shippingSubdivision}
fullWidth
onChange={(e) => setShippingSubdivision(e.target.value)}
>
{Object.entries(shippingSubdivisions)
.map(([code, name]) => ({ id: code, label: name }))
.map((item) => (
<MenuItem key={item.id} value={item.id}>
{item.label}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>Shipping Options</InputLabel>
<Select
value={shippingOption}
fullWidth
onChange={(e) => setShippingOption(e.target.value)}
>
{shippingOptions
.map((sO) => ({
id: sO.id,
label: `${sO.description} - (${sO.price.formatted_with_symbol})`,
}))
.map((item) => (
<MenuItem key={item.id} value={item.id}>
{item.label}
</MenuItem>
))}
</Select>
</Grid>
</Grid>
<br />
<div style={{ display: "flex", justifyContent: "space-between" }}>
<Button component={Link} variant="outlined" to="/cart">
Back to Cart
</Button>
<Button type="submit" variant="contained" color="primary">
Next
</Button>
</div>
</form>
</FormProvider>
</div>
);
};
export default AddressForm;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
This was a commercejs.com issue not a coding issue

React <Switch> is not getting updated or changing its state

Hey guys I am learning react and have a form to edit book details. I am using django in the backend. I am not able to update the e-book which is a switch to turn on and off according to whether e-book is available or not. The switch works fine, but no data is being changed in the database. I am confused on how to work with the switch and saw lots of resources saying different things which is quite difficult to understand. Rest of the fields are getting updated correctly. Can someone tell me what changes I have to make in this switch to make it work??
code
import React, {useEffect, useState} from 'react'
import axiosInstance from '../../axios';
import { useForm, Controller } from 'react-hook-form';
//MaterialUI
import Button from '#material-ui/core/Button';
import CssBaseline from '#material-ui/core/CssBaseline';
import TextField from '#material-ui/core/TextField';
import Grid from '#material-ui/core/Grid';
import Typography from '#material-ui/core/Typography';
import { makeStyles } from '#material-ui/core/styles';
import Container from '#material-ui/core/Container';
import FormControlLabel from '#material-ui/core/FormControlLabel';
import Switch from '#material-ui/core/Switch';
import Select from '#material-ui/core/Select';
import InputLabel from '#material-ui/core/InputLabel';
import MenuItem from '#material-ui/core/MenuItem';
import FormControl from '#material-ui/core/FormControl';
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(8),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
bookformbody: {
display: "flex",
backgroundColor: "#ffff",
height: "100vh",
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing(3),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
function BookEdit() {
const initialFormData = Object.freeze({
id: '',
summary: '',
published_date: '',
e_book: false,
});
const [formData, updateFormData] = useState(initialFormData);
useEffect(() => {
axiosInstance.get('api/books/details/view/').then((res) => {
updateFormData({
...formData,
['summary']: res.data.summary,
['published_date']: res.data.published_date,
['e_book']: res.data.e_book,
});
console.log(res.data);
});
}, [updateFormData]);
const handleChange = (e) => {
if(e.target.name === "e_book"){
return(
updateFormData({
...formData,
[e.target.name]: e.target.checked
})
)
}
updateFormData({
...formData,
// Trimming any whitespace
[e.target.name]: e.target.value
});
};
const onSubmit = (data) =>{
let formData = new FormData();
formData.append('summary', data.summary);
formData.append('published_date', data.published_date);
formData.append('e_book', data.e_book);
axiosInstance.put('api/books/details/edit/', formData);
} ;
const classes = useStyles();
const { register, handleSubmit, control, errors } = useForm();
return (
<>
<Header />
<div className={classes.bookformbody}>
<SideBar />
<Container component="main" maxWidth="sm">
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Edit Book Details
</Typography>
<form className={classes.form} noValidate onSubmit={handleSubmit(onSubmit)}>
<Grid container spacing={2}>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
id="summary"
label="Book Summary"
name="summary"
autoComplete="summary"
value={formData.summary}
onChange={handleChange}
inputRef={register({maxLength: 1000})}
multiline
rows={4}
/>
</Grid>
<Grid item xs={12}>
<TextField
variant="outlined"
required
fullWidth
type="date"
label="Published Date"
name="published_date"
autoComplete="published_date"
value={formData.published_date}
onChange={handleChange}
inputRef={register({required: true})}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<InputLabel id="e-book-switch">E-Book</InputLabel>
<Controller
name="e_book"
control={control}
as={
<Switch size="small"
id="e-book-switch"
type="checkbox"
name="e_book"
onChange={handleChange}
// inputRef={register}
value={formData.e_book}
checked={formData.e_book}
/>
}
/>
</Grid>
</Grid>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Update
</Button>
</form>
</div>
</Container>
</div>
</>
)
}
export default BookEdit;
You are passing props to Switch directly, but what you should do is to use Controller props, and Controller will then pass it down to Switch:
<Controller as={Switch} value={formData.e_book} ... />
Otherwise you need to use render, not as
This is actually described pretty good here:
https://react-hook-form.com/api/#Controller
UPDATE
Here is the sandbox where it is working fine with above changes - https://codesandbox.io/s/kind-nash-s94v0
What i did there is simply this:
<Controller
name="e_book"
control={control}
render={(props) => {
return (
<Switch
size="small"
id="e-book-switch"
type="checkbox"
name="e_book"
onChange={handleChange}
// inputRef={register}
value={formData.e_book}
checked={formData.e_book}
/>
);
}}
/>
You are initializing the value as a string at the beginning of BookEdit(). Try to set initialFormData like this:
const initialFormData = Object.freeze({
id: '',
summary: '',
published_date: '',
e_book: false,
});

Resetting a form when using onBlur as opposed to onChange

I had a form that has a lot of lag due to a large amount of state being handled for user's with a large number of job posts etc. I am trying to subdue this lag my switching my onChange to onBlur, this works great. The only problem is that my form no longer gets set to InitialState( empty string). I also have a submit button that I am keeping invalid until all inputs are filled. due to the onblur it remains invalid until I click away from the form. Is there a way I can still reset a form when using onBlur?? and does anyone have a solution to the issue of my button remaining invalid until I click away from the form. My inputs code are as follows:
the handleSubmit function:
const handleSubmit = async e => {
e.preventDefault()
setIsLoading(true)
const fireToken = await localStorage.FBIdToken
await axios
.post(`/job`, formData, {
headers: {
Authorization: `${fireToken}`
}
})
.then(res => {
setOpen(true)
setMessage(res.data)
fetchUser()
setIsLoading(false)
setIsModalOpen(false)
setFormData(INITIAL_STATE)
})
.catch(err => {
setErrors(err.response.data)
console.log(err)
setIsLoading(false)
})
}
The form code:
import React from 'react'
// components
import SelectStatus from './SelectStatus'
// Material UI Stuff
import CircularProgress from '#material-ui/core/CircularProgress'
import Typography from '#material-ui/core/Typography'
import TextField from '#material-ui/core/TextField'
import CardContent from '#material-ui/core/CardContent'
import Button from '#material-ui/core/Button'
import Card from '#material-ui/core/Card'
import Grid from '#material-ui/core/Grid'
// JobCardStyles
import useJobCardStyles from '../styles/JobCardStyles'
const NewJobForm = React.forwardRef(
({ handleSubmit, formData, handleInputChange, isloading }, ref) => {
const { company, position, status, link } = formData
const isInvalid = !company || !position || !link || !status || isloading
const classes = useJobCardStyles()
return (
<Card className={classes.card}>
<CardContent className={classes.content}>
<form noValidate onSubmit={handleSubmit} className={classes.form}>
<Grid
container
spacing={2}
alignItems="center"
justify="space-between"
>
<Grid item sm="auto" xs={12} className={classes.grid}>
<Typography>New</Typography>
<Typography>Job</Typography>
</Grid>
<Grid item sm={3} xs={12} className={classes.grid}>
<TextField
className={classes.jobField}
margin="normal"
fullWidth
id="company"
type="company"
label="Company"
name="company"
autoComplete="company"
defaultValue={company}
onBlur={handleInputChange('company')}
/>
</Grid>
<Grid item sm={3} xs={12} className={classes.grid}>
<TextField
className={classes.jobField}
margin="normal"
fullWidth
id="position"
type="position"
label="Position"
name="position"
autoComplete="position"
defaultValue={position}
onBlur={handleInputChange('position')}
/>
</Grid>
<Grid item sm={2} xs={12} className={classes.grid}>
<SelectStatus
status={status}
handleInputChange={handleInputChange}
/>
</Grid>
<Grid item sm={2} xs={12} className={classes.grid}>
<TextField
className={classes.jobField}
margin="normal"
fullWidth
id="link"
type="text"
label="Link"
name="link"
autoComplete="link"
defaultValue={link}
onBlur={handleInputChange('link')}
/>
</Grid>
<Grid item sm={1} xs={12} className={classes.grid}>
<Button
fullWidth
type="submit"
variant="contained"
color="primary"
disabled={isInvalid}
className={classes.submit}
disableElevation
>
Submit
{isloading && (
<CircularProgress size={30} className={classes.progress} />
)}
</Button>
</Grid>
</Grid>
</form>
</CardContent>
</Card>
)
}
)
export default NewJobForm
Try making another function to wrap several functions.
const NewJobForm = React.forwardRef(
//other logic
const reset = () => {//your reset function logic}
//ver 1
const handleOnBlur = (fn, relatedParam) => {
reset();
fn(relatedParam);
}
//ver 2
const handleOnBlur = (relatedParam) => {
reset();
handleInputChange(relatedParam);
}
return (
<TextField
//other props
onBlur={() => handleOnBlur('company')}
/>
)

React - Can't find the leak, infinite state declaration suspected

I'm a complete beginner in React and I was pretty happy with my first app since I, maybe, have a memory leak ? My app is very laggy after entering value in the input, after click on the add button, at bottom right, and I suspect that I don't use 'useState' like I should ? I dunno, I've been searching for hours :( ...
Here's the app : https://n3g.gitlab.io/react-conso-energie/
Here's the code :
In the App.js (parent) :
import React, { useState } from 'react'
import firebase from './firebase'
import AddForm from './AddForm'
import ListingTable from './ListingExpansionPanels'
import moment from 'moment'
// MATERIAL UI
import { CssBaseline } from '#material-ui/core'
import Grid from '#material-ui/core/Grid'
import Snackbar from '#material-ui/core/Snackbar'
import MuiAlert from '#material-ui/lab/Alert'
import './styles.css'
export default function App () {
// BDD
const dbRef = firebase.database().ref('items')
// LISTING DATA
const [listingData, setListingData] = useState([{}])
dbRef.once('value', (snapshot) => {
const releves = snapshot.val()
const listingData = []
for (const [key, releve] of Object.entries(releves)) {
listingData.push({
key: key,
month: releve.month,
gaz: releve.gaz,
electricite: releve.electricite,
total: releve.total,
submissionDate: releve.submissionDate
})
}
const listingDataSorted = listingData.sort((a, b) => (a.submissionDate > b.submissionDate) ? 1 : -1)
setListingData(listingDataSorted)
})
const lastItemIndex = listingData.length - 1
// MONTHS
const [selectedDate, handleDateChange] = useState(new Date())
const dateFormat = moment(selectedDate).format('MMMM')
// ELECTRICITÉ
const constElec = { prix: 0.15356, abo: 117.56 }
const [kw, setKw] = useState('')
const diffElec = kw - listingData[lastItemIndex].electricite
const resultatElec = Math.round((constElec.prix * diffElec + (constElec.abo / 12)) * 1e2) / 1e2
// GAZ
const constGaz = { prix: 0.0681, abo: 215.73, indice: 11.34 }
const [m3, setm3] = useState('')
const diffGaz = m3 - listingData[lastItemIndex].gaz
const resultatGaz = Math.round((((constGaz.indice * diffGaz) * constGaz.prix) + (constGaz.abo / 12)) * 1e2) / 1e2
// TOTAL
const total = Math.round((resultatElec + resultatGaz) * 1e2) / 1e2
// SUBMIT
const handleSubmit = () => {
const releve = {
submissionDate: moment(selectedDate).unix(),
month: dateFormat,
gaz: m3,
electricite: kw,
total: total
}
dbRef.push(releve)
setOpenSnack(true)
setm3('')
setKw('')
}
// DELETE
const handleDelete = key => {
dbRef.child(key).remove()
}
// SNACKBAR
function Alert (props) {
return <MuiAlert elevation={6} variant='filled' {...props} />
}
const [openSnack, setOpenSnack] = React.useState(false)
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return
}
setOpenSnack(false)
}
return (
<>
<CssBaseline />
<div className='App'>
<Grid container justify='center' spacing={2}>
<Grid item xs={12}>
<h1>Conso Energie</h1>
<AddForm m3={m3} setm3={setm3} kw={kw} setKw={setKw} selectedDate={selectedDate} handleDateChange={handleDateChange} handleSubmit={handleSubmit} />
</Grid>
<Grid item xs={12}>
<ListingTable listingData={listingData} handleDelete={handleDelete} />
</Grid>
</Grid>
<Snackbar open={openSnack} autoHideDuration={3500} onClose={handleClose}>
<Alert onClose={handleClose} severity='success'>
Sauvegardé
</Alert>
</Snackbar>
</div>
</>
)
}
In the AddForm.js (child - I'm using Material UI) :
import React from 'react'
import TextField from '#material-ui/core/TextField'
import InputAdornment from '#material-ui/core/InputAdornment'
import Button from '#material-ui/core/Button'
import CloudUploadIcon from '#material-ui/icons/CloudUpload'
import { MuiPickersUtilsProvider, DatePicker } from '#material-ui/pickers'
import MomentUtils from '#date-io/moment'
import moment from 'moment'
import 'moment/locale/fr'
import Dialog from '#material-ui/core/Dialog'
import DialogActions from '#material-ui/core/DialogActions'
import DialogContent from '#material-ui/core/DialogContent'
import DialogTitle from '#material-ui/core/DialogTitle'
import Fab from '#material-ui/core/Fab'
import AddIcon from '#material-ui/icons/Add'
export default function AddForm ({ m3, setm3, kw, setKw, handleSubmit, selectedDate, handleDateChange }) {
const handleUpdateGaz = function (event) {
setm3(Number(event.target.value))
}
const handleUpdateKw = function (event) {
setKw(Number(event.target.value))
}
moment.locale('fr')
const [open, setOpen] = React.useState(false)
const handleClickOpenAddDialog = () => {
setOpen(true)
}
const handleCloseAddDialog = () => {
setOpen(false)
}
return (
<>
<div>
<Fab className='fab-btn-add' color='primary' aria-label='add' onClick={handleClickOpenAddDialog}>
<AddIcon />
</Fab>
<Dialog
open={open}
onClose={handleCloseAddDialog}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>Entrer les valeurs</DialogTitle>
<DialogContent>
<form className='addform' noValidate autoComplete='off'>
<MuiPickersUtilsProvider utils={MomentUtils}>
<DatePicker
inputVariant='outlined'
value={selectedDate}
onChange={handleDateChange}
label='Mois'
format='MMMM Y'
views={['month']}
minDate={new Date('2020-01-01')}
maxDate={new Date('2020-12-31')}
/>
</MuiPickersUtilsProvider>
<TextField
label='Electricité'
variant='outlined'
type='number'
InputProps={{
endAdornment: <InputAdornment position='end'>kW</InputAdornment>
}}
value={kw}
onChange={handleUpdateKw}
/>
<TextField
label='Gaz'
variant='outlined'
type='number'
InputProps={{
endAdornment: <InputAdornment position='end'>m3</InputAdornment>
}}
value={m3}
onChange={handleUpdateGaz}
/>
<Button
className='btn-submit'
size='large'
variant='contained'
color='primary'
startIcon={<CloudUploadIcon />}
onClick={handleSubmit}
>
Confirmer
</Button>
</form>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseAddDialog} color='primary' autoFocus>
Retour
</Button>
</DialogActions>
</Dialog>
</div>
</>
)
}
Pretty sure it's unrelated but here's the ListingExpansionPanel.js
import React from 'react'
import ExpansionPanel from '#material-ui/core/ExpansionPanel'
import ExpansionPanelSummary from '#material-ui/core/ExpansionPanelSummary'
import ExpansionPanelDetails from '#material-ui/core/ExpansionPanelDetails'
import Typography from '#material-ui/core/Typography'
import ExpandMoreIcon from '#material-ui/icons/ExpandMore'
import Icon from '#material-ui/core/Icon'
import Grid from '#material-ui/core/Grid'
import Button from '#material-ui/core/Button'
import Chip from '#material-ui/core/Chip'
import SwipeableViews from 'react-swipeable-views'
export default function ListingTable ({ listingData, handleDelete }) {
const dataRow = listingData.map((data, key) => (
<ExpansionPanel key={key} className='relevePanel'>
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon />}
aria-controls={key}
id={key}
>
<Typography>
<span>
<Icon style={{ marginRight: 15 }}>calendar_today</Icon>
{data.month}<b>{data.total ? ' : ' + data.total + ' €' : ''}</b>
</span>
</Typography>
</ExpansionPanelSummary>
<ExpansionPanelDetails>
<SwipeableViews>
<Typography className='expansion-detail'>
<Grid container>
<Grid item xs={12}>
<b style={{ color: '#cacaca' }}>2020</b>
</Grid>
<Grid item xs>
<Icon>power</Icon>
<span>{data.electricite} <small>Kwh</small></span>
<div>
<Chip className='plus' size='small' label='+3,4%' />
</div>
</Grid>
<Grid item xs>
<Icon>whatshot</Icon>
<span>{data.gaz} <small>m<sup>3</sup></small></span>
<div>
<Chip className='moins' size='small' label='-5,2%' />
</div>
</Grid>
<Grid item xs={12}>
<Button
className='btnRemove'
style={{ marginTop: 15 }}
size='small'
color='secondary'
onClick={() => handleDelete(data.key)}
>
Supprimer
</Button>
</Grid>
</Grid>
</Typography>
<Typography className='expansion-detail'>
<Grid container>
<Grid item xs={12}>
<b style={{ color: '#cacaca' }}>2019</b>
</Grid>
<Grid item xs>
<Icon>power</Icon>
<span>{data.electricite} <small>Kwh</small></span>
<div>
<Chip className='plus' size='small' label='+3,4%' />
</div>
</Grid>
<Grid item xs>
<Icon>whatshot</Icon>
<span>{data.gaz} <small>m<sup>3</sup></small></span>
<div>
<Chip className='moins' size='small' label='-5,2%' />
</div>
</Grid>
<Grid item xs={12}>
<Button
className='btnRemove'
style={{ marginTop: 15 }}
size='small'
color='secondary'
onClick={() => handleDelete(data.key)}
>
Supprimer
</Button>
</Grid>
</Grid>
</Typography>
</SwipeableViews>
</ExpansionPanelDetails>
</ExpansionPanel>
))
return (
<>
{dataRow}
</>
)
}
Thank you A LOT for your help, if someone see something.
I continue to search..
Thanks.
Update : Added the whole code for this 2 files
Update 2 : When I disable the firebase link, it's ok ! So I'll investigate this way..
This won't solve your problem but one thing that will use less memory is not creating an anonymous function, but replacing it with a reference in child components.
In the AddForm.js :
// pass the reference to changeKw instead of creating an anonymous function:
<TextField
value={kw}
onChange={changeKw} // e will be passed automatically
/>
In the App.js (parent) :
const changeKw = e => {
console.log(e.target.value) // e gets passed
setKw(e.target.value)
}

Verify mock function is called on button click when using withFormik's handleSubmit

I have a simple component with some inputs, I am trying to verify whether a mock function is called after a button is clicked.
Here is what I tried in my test file:
import React from 'react'
import { mount } from 'enzyme'
import AddUser from '../Components/AddUserWithFormik'
import { Router } from 'react-router-dom'
import { createBrowserHistory } from 'history'
import * as Constants from '../actions/actionTypes'
const hist = createBrowserHistory()
describe('AddUser page', () => {
let wrapper
const mockFetchDetailsActions = jest.fn()
const mockHandleCancel = jest.fn()
const mockHandleInputChangeAction = jest.fn()
const mockHandleSubmit = jest.fn()
const match = {
params: {
id: '12345'
}
}
const location = {
pathname: '/add_user',
search: '',
hash: '',
key: 'ph0ovl'
}
const user = {
first_name: '',
last_name: '',
email: '',
email_secondary: '',
mobile_phone: '',
work_phone: ''
}
beforeEach(() => {
wrapper = mount(
<Router history={hist}>
<AddUser
match={match}
location={location}
user={user}
handleSubmit={mockHandleSubmit}
actions={{
fetchDetailsActions: mockFetchDetailsActions,
handleCancel: mockHandleCancel,
handleInputChangeAction: mockHandleInputChangeAction
}}
/>
</Router>
)
})
describe('#ComponentsRendered', () => {
it('verify simulate change on all input elements', () => {
wrapper
.find('button')
.at(0)
.simulate('click')
expect(mockHandleSubmit).toHaveBeenCalled()
})
})
})
Here is my component:
/* eslint-disable no-invalid-this */
import React, { Fragment } from 'react'
import PropTypes from 'prop-types'
import { withStyles } from '#material-ui/core/styles'
import GridContainer from './Grid/GridContainer'
import GridItem from './Grid/GridItem'
import { TextField } from 'formik-material-ui'
import { Field, Form } from 'formik'
import dashboardStyle from '../styles/dashboardStyle'
import Card from './Card/Card'
import CardBody from './Card/CardBody'
import * as Constants from '../actions/actionTypes'
import SaveAndCancelButtons from './Common/saveAndCancelButtons'
class AddUser extends React.Component {
componentDidMount () {
if (this.props.match.params.id) {
this.props.actions.fetchDetailsActions(Constants.FETCH_DETAILS_API_CALL_REQUEST, this.props.match.params.id)
} else {
this.props.actions.handleCancel()
}
}
render () {
const { classes, isFetching } = this.props
return (
<Form>
<Field
name="user"
render={feildProps => (
<Fragment>
<GridContainer>
<GridItem xs={12} sm={12} md={12}>
<Card>
<h2 className={classes.cardTitleWhite}>Add User</h2>
<CardBody isFetching={isFetching}>
<GridContainer>
<GridItem xs={12} sm={12} md={4}>
<Field
label="First Name"
name={`user.first_name`}
className={this.props.classes.textField}
margin="normal"
variant="outlined"
component={TextField}
/>
<Field
label="Secondary Email"
name={`user.email_secondary`}
className={this.props.classes.textField}
margin="normal"
variant="outlined"
component={TextField}
/>
</GridItem>
<GridItem xs={12} sm={12} md={4}>
<Field
label="Last Name"
name={`user.last_name`}
className={this.props.classes.textField}
margin="normal"
variant="outlined"
component={TextField}
/>
<Field
label="Mobile Phone"
name={`user.mobile_phone`}
className={this.props.classes.textField}
margin="normal"
variant="outlined"
component={TextField}
/>
</GridItem>
<GridItem xs={12} sm={12} md={4}>
<Field
label="Email"
name={`user.email`}
className={this.props.classes.textField}
margin="normal"
variant="outlined"
component={TextField}
/>
<Field
label="Work Phone"
name={`user.work_phone`}
className={this.props.classes.textField}
margin="normal"
variant="outlined"
component={TextField}
/>
</GridItem>
</GridContainer>
</CardBody>
</Card>
<SaveAndCancelButtons
handleSave={() => {
this.props.handleSubmit()
}}
routingLink="/people"
label="Save"
/>
</GridItem>
</GridContainer>
</Fragment>
)}
/>
</Form>
)
}
}
AddUser.propTypes = {
classes: PropTypes.object.isRequired
}
export default withStyles(dashboardStyle)(AddUser)
Here is my withFormik() wrapper:
import { withStyles } from '#material-ui/core/styles'
import { withFormik } from 'formik'
import * as Yup from 'yup'
import AddUser from './AddUser'
import * as Constants from '../actions/actionTypes'
const styles = theme => ({
textField: {
width: '100%'
}
})
const onSave = props => {
const userDetails = {
user: props.user
}
if (userDetails && userDetails.user.id) {
props.actions.updateDetailsActions(Constants.UPDATE_USER_API_CALL_REQUEST, userDetails.user.id, userDetails)
} else {
props.actions.addNewUserAction(Constants.ADD_USER_API_CALL_REQUEST, userDetails)
}
}
const validations = Yup.object().shape({
user: Yup.object().shape({
first_name: Yup.string().required('Required'),
last_name: Yup.string().required('Required'),
email: Yup.string().required('Required')
})
})
const withFormikWrapper = withFormik({
validationSchema: validations,
enableReinitialize: true,
handleSubmit: props => {
onSave(props)
}
})(AddUser)
export default withStyles(styles)(withFormikWrapper)
Expected result:
I expect that the mockHandleSubmit is called when the simulate click is happening.
Actual Results:
expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called, but it was not called.
123 | // console.log(wrapper.debug())
124 |
> 125 | expect(mockHandleSubmit).toHaveBeenCalled()
| ^
126 | })
127 | })
128 | })
at Object.toHaveBeenCalled (src/test/AddUser.test.js:125:32)
Here is the saveAndCancelButton component:
import React, { Component } from 'react'
import RoutingButton from './RoutingButton'
import { withStyles } from '#material-ui/core/styles'
import GridContainer from '../Grid/GridContainer'
import GridItem from '../Grid/GridItem'
import ClientContactsStyles from '../../styles/ClientsContactsStyles'
import SaveIcon from '#material-ui/icons/Save'
import Close from '#material-ui/icons/Close'
import classNames from 'classnames'
import Button from '#material-ui/core/Button'
class SaveAndCancelButtons extends Component {
render () {
const { classes } = this.props
const close = <Close />
return (
<GridContainer>
<GridItem xs={12} sm={12} md={6}>
{this.props.submitButtonProps ? (
<GridItem xs={12} sm={12} md={6}>
<Button
variant="contained"
size="large"
className={classes.button}
onClick={this.props.handleSubmit}
>
Submit
</Button>
</GridItem>
) : null}
</GridItem>
<GridItem xs={12} sm={12} md={3}>
<Button
variant="contained"
size="large"
className={classes.button}
onClick={this.props.handleSave}
>
<SaveIcon
className={classNames(classes.leftIcon, classes.iconSmall)}
/>
{this.props.label}
</Button>
</GridItem>
<GridItem xs={12} sm={12} md={3}>
<RoutingButton
variant="contained"
size="large"
className={classes.button}
buttonIcon={close}
routingLink={this.props.routingLink}
label="Cancel"
/>
</GridItem>
</GridContainer>
)
}
}
export default withStyles(ClientContactsStyles)(SaveAndCancelButtons)
The problem here is jest function is not waiting for formik to call its onSubmit() function. To resolve this jest provides 'wait' api. See the below code.
await wait(() => {
expect(mockHandleSubmit).toHaveBeenCalled()
});
Happy Coding :)
I don't think submit is being called because your user is not passing your validation. Rectify that and use below for expectation.
xxxxxx
Given that you have omitted test code in your post that satisfies the schema above is not the solution. The solution is to do expectations against the actions. It is not possible to mock handleSubmit as this is dealt with by the withFormik wrapper.
xxxxxx
it('verify simulate change on all input elements', async () => {
wrapper.find('button').at(0).simulate('click')
await new Promise(resolve=>{
setTimeout(()=>resolve(),0);
})
expect(mockHandleSubmit).toHaveBeenCalled()
})

Categories

Resources