invalid Invalid left-hand side in arrow function parameters (43:13) - reactjs

hello im a noob in react and am trying to pass the car.id using props to my editcar component so i can update it via firebase , however im getting a an error Invalid left-hand side in arrow function parameters (43:13) any idea how i can pass the car.id to edit function? thanks for the help!
admin_cars.js
<ul className="TaskList">
{
Cars.map(car => (
<tr>
<th scope="row">{car.id}</th>
<td>{car.year}</td>
<td>{car.make}</td>
<td>{car.model}</td>
<td>{car.body_type}</td>
<td>{car.int_color}</td>
<td><img src={car.link} height="92" /> </td>
<td>{car.price}</td>
<td>{car.status ? "Available" : "Sold"}</td>
<td>
<Link to={`/admin/editcar/${this.props.car.id}`}>
<Icon icon={pencil} />
</Link>
</td>
</tr>
))
}
</ul>
edit_car.js
import { CarsRef, timeRef } from './reference';
class EditCar extends Component {
state = {
year: '',
make: '',
model: '',
trim: '',
engine: '',
drive_type: '',
body_type: '',
ext_color: '',
int_color: '',
transmission: '',
price: 0,
sale: 0,
status: true,
vin: '',
link: '',
elect_stab: '',
wireless: '',
seat: '',
keyless: '',
trip_comp: '',
tire_pressure: '',
wiper: '',
id:'',
headlight: '',
alertMsg: false
}
editcar = (e, car.id) => {
alert(this.car.id)
e.preventDefault();
const NewCar= {
body_type: this.state.body_type.trim(),
wiper: this.state.wiper,
headlight: this.state.headlight,
make: this.state.make,
link: this.state.link,
engine: this.state.engine,
transmission:this.state.transmission,
vin:this.state.vin,
seat: this.state.seat,
price: this.state.price,
ext_color: this.state.ext_color,
checked: false,
starred: false,
timestamp: timeRef
};
CarsRef.child().update(NewCar);
this.setState({ body_type: '' });
this.setState({ wiper: '' });
this.setState({ make: '' });
this.setState({link:''});
this.setState({ headlight: '' });
this.setState({price: ''});
this.setState({transmission: ''});
this.setState({engine: ''});
this.setState({vin: ''});
this.setState({ext_color: ''});
this.setState({id: ''})
}

I think this might be related to your editcar method. The second parameter is not valid and you probably meant for it to be car and not car.id, so:
change
editcar = (e, car.id) => {}
to
editcar = (e, car) => {}

Related

re-render not behaving properly

So I deployed the app to demonstrate the problem
https://ecstatic-mayer-aaa530.netlify.app/
When you 'refresh' the page new data is fetched and user name is displayed (along with active state)
BUT when I click random user button, I don't get the same behavior even though I refetch the data. I want to get the same behavior as page refresh. (Name is displayed with the active state)
To better observe the problem you can : Hover on other fields, click on random user btn and then re-enter with your mouse on name (profile icon). It is not updating as you'll see
import './App.css';
import ProfileCard from './components/ProfileCard';
import React, { useEffect, useState } from 'react';
function App() {
const [userData, setUserData] = useState({});
const [triggerFetch, setTriggerFetch] = useState(false);
const fetchUserData = async () => {
const response = await fetch('https://randomuser.me/api/');
const data = await response.json();
setUserData(setFields(data.results[0]));
};
const setFields = (userData) => {
const fName = userData.name.first;
const lName = userData.name.last;
const fullName = fName + ' ' + lName;
return {
image: userData.picture.large,
name: fullName,
email: userData.email,
dob: userData.dob.date,
location: userData.location.street.name,
phone: userData.phone,
password: userData.login.password,
};
};
useEffect(() => {
fetchUserData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [triggerFetch]);
//this triggers fetch
const handleRandomUserClick = () => {
setTriggerFetch(!triggerFetch);
};
return (
<main>
<div className='grey-bg'></div>
<ProfileCard
userData={userData}
handleRandomUserClick={handleRandomUserClick}
/>
</main>
);
}
export default App;
import React from 'react';
import {
FaUserAlt,
FaPhoneAlt,
FaBirthdayCake,
FaLock,
FaLocationArrow,
FaEnvelope,
} from 'react-icons/fa';
const ProfileCard = ({ userData, handleRandomUserClick }) => {
const { image, name, email, dob, location, phone, password } = userData;
const [randomUserClicked, setrandomUserClicked] = React.useState(false);
const defaultFlag = {
name: 'active',
email: '',
dob: '',
location: '',
phone: '',
password: '',
};
const [flag, setFlag] = React.useState(defaultFlag);
const [title, setTitle] = React.useState('My Name Is');
const [value, setValue] = React.useState(name);
const handleValue = (e) => {
if (e.target.dataset.label === 'name') {
setTitle('My Name is');
setValue(name);
setFlag(defaultFlag);
} else if (e.target.dataset.label === 'email') {
setTitle('My Email is');
setValue(email);
setFlag({
name: '',
email: 'active',
dob: '',
location: '',
phone: '',
password: '',
});
} else if (e.target.dataset.label === 'dob') {
setTitle('My Birthday is');
setValue(new Date(dob).toLocaleDateString());
setFlag({
name: '',
email: '',
dob: 'active',
location: '',
phone: '',
password: '',
});
} else if (e.target.dataset.label === 'location') {
setTitle('I live in');
setValue(location);
setFlag({
name: '',
email: '',
dob: '',
location: 'active',
phone: '',
password: '',
});
} else if (e.target.dataset.label === 'phone') {
setTitle('My phone number is');
setValue(phone);
setFlag({
name: '',
email: '',
dob: '',
location: '',
phone: 'active',
password: '',
});
} else {
setTitle('My password');
setValue(password);
setFlag({
name: '',
email: '',
dob: '',
location: '',
phone: '',
password: 'active',
});
}
if (e.target.dataset.label === 'random') {
handleRandomUserClick();
setrandomUserClicked(!randomUserClicked);
}
};
React.useEffect(() => {
setTitle('My Name is');
setValue(name);
setFlag(defaultFlag);
}, [randomUserClicked]);
return (
<article className='profile-card'>
<img src={image} alt={name} />
<div className='user-details'>
<p className='user-title'>{title}</p>
<h3 className='user-value'>{value || name}</h3>
</div>
<ul className='card-list'>
<li className={flag.name} onMouseEnter={handleValue} data-label='name'>
<FaUserAlt className='icon' />
</li>
<li
data-label='email'
onMouseEnter={handleValue}
className={flag.email}
>
<FaEnvelope className='icon' />
</li>
<li data-label='dob' onMouseEnter={handleValue} className={flag.dob}>
<FaBirthdayCake className='icon' />
</li>
<li
data-label='location'
onMouseEnter={handleValue}
className={flag.location}
>
<FaLocationArrow className='icon' />
</li>
<li
data-label='phone'
onMouseEnter={handleValue}
className={flag.phone}
>
<FaPhoneAlt className='icon' />
</li>
<li
data-label='password'
onMouseEnter={handleValue}
className={flag.password}
>
<FaLock className='icon' />
</li>
</ul>
{/* Also handling this click within handleValue function */}
<button className='btn' onClick={handleValue} data-label='random'>
Random User
</button>
</article>
);
};
export default ProfileCard;
The problem happens, because in ProfileCard component, userData is not listed under useEffects's dependencies array.
By the way, your component design is very prone to bugs. In React functional components should be a simple functions that receive some data (props) and return JSX. Hooks should be used only when you actually have to use them. In your app, you're creating a complicated network of effects, state updates and re-renders, which makes it hard to maintain.
Let's write all hooks you actually need:
one state for the data fetched from an api
one state for keeping which section is currently active (name, email, etc.)
one effect for fetching the data
And that's it! Everything else can be just passed through props.

ReactJS Add new row to Table

I create Table dynamicaly:
In component Table I set the default values of table in json:
constructor(props) {
super(props);
this.state = {
data: [
{'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': ''}
]
};
}
Then use it to render table:
render() {
return (
<div className={styles}>
<table>
<thead>
<tr>{this.getHeader()}</tr>
</thead>
<tbody>
{this.getRowsData()}
</tbody>
<button onClick={this.addRow}>
Add new row
</button>
</table>
</div>
);
}
This is a methods realization:
getKeys = function () {
return Object.keys(this.state.data[0]);
};
getHeader = function () {
var keys = this.getKeys();
return keys.map((key, index) => {
return <th key={key}>{key.toLowerCase()}</th>
})
};
getRowsData = function () {
var items = this.state.data;
var keys = this.getKeys();
return items.map((row, index) => {
return <tr key={index}><RenderRow key={index} data={row} keys={keys}/></tr>
})
};
And now I try to add new row, using this method:
addRow = function () {
let newRows = this.state.data.push({'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': ''});
this.setState({data: newRows});
};
But when I try it, I receive the following error: TypeError: Cannot convert undefined or null to object
in
return Object.keys(this.state.data[0]);
Indeed, after I push a new object to "data", I see, that "data" not containts any elements. Although before that it contained 1 element: {'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': ''}
This is the wrong in your function. Push will return you the values that pushed into the array,
addRow = () => {
let existingRows = this.state.data;
existingRows.push({'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': ''});
this.setState({ data: existingRows });
};
If You wish to use arrow function for addRow the below will not be needed! Or if you wish to use the normal function you are using you have to change the button onClick as below,
addRow = function () {
let existingRows = this.state.data;
existingRows.push({ 'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': '' });
this.setState({ data: existingRows });
};
<button onClick={() => this.addRow()}>
Add new row
</button>
The value of newRows will be {'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': ''} which you are setting as state instead it should be an array.
So what you can do is:-
let rowsData = this.state.data;
existingRows.push({ 'Date': '', 'Operation': '', 'Amount': '', 'Item_of_expenditure': '', 'Balance': '' });
this.setState({ data: rowsData });

NextJS: Use same component in multiple routes for multiple pages

In my NextJS app, I have a search bar component OrderSearchBar.js and I want to use it in both index.js and /purchases.js pages but with different endpoints.For example,if I click search button on the index.js page,it should post form content to /orders and on the /purchases.js, form content should post to /purchaseDetails.Is there any way to accomplish this?
OrderSearchBar.js
class OrderSearchBar extends Component{
constructor(props) {
super(props);
this.onChangeInput = this.onChangeInput.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
nature: '',
type: '',
searchBy: '',
startDate: '',
endDate: '',
keyword: ''
}
}
onChangeInput(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
const t = {
nature: this.state.nature,
type: this.state.type,
searchBy: this.state.searchBy,
startDate: this.state.startDate,
endDate: this.state.endDate,
keyword: this.state.keyword
}
axios.post('/search', t)..then(res => console.log(res.data));
/*I can do this for single endpoint.but how do I add multiple endpoints
for use in different pages?*/
this.setState({
nature: '',
type: '',
searchBy: '',
startDate: '',
endDate: '',
keyword: ''
});
}
You can differentiate the current location in your orderSearchBar.js
by getting the pathname of window.location object.
onSubmit(e) {
e.preventDefault();
const t = {
nature: this.state.nature,
type: this.state.type,
searchBy: this.state.searchBy,
startDate: this.state.startDate,
endDate: this.state.endDate,
keyword: this.state.keyword
}
const pathName = window && window.location.pathname;
const destination = (pathName === '/purchases') ? '/purchaseDetails' : '/orders'
axios.post(destination, t)..then(res => console.log(res.data));
this.setState({
nature: '',
type: '',
searchBy: '',
startDate: '',
endDate: '',
keyword: ''
});
}
While you could use window property, this might not work if you're using Nuxt.js or other server side rendering, since the window object is not present.
Instead, I suggest you pass a prop down to your component, say:
<component :type="'isPurchaseDetails'">
or for purchases
<component :type="'isPurchases'">

React - state won't update

i am building small react app and i have strange situation that state won't update. Here is example:
class App extends Component {
constructor() {
super();
this.state = {
locale: 'de',
countryList: [],
fetchInProgress: true,
serverError: {},
person: {
salutation: '',
firstName: '',
lastName: '',
birthDate: '',
nationality: '',
address: '',
zipCode: '',
city: '',
country: '',
mobileNumber: '',
email: '',
correspondanceLanguage: '',
}
};
}
componentDidMount() {
this.setState({
fetchInProgress: false
}),()=>console.log('State updated', this.state)
}
}
I tried also using other approaches:
componentDidMount() {
const temp = {...this.state};
temp.fetchInProgress = false;
this.setState(temp),()=>console.log('State updated', this.state)
}
componentDidMount() {
const temp = {...this.state};
temp['fetchInProgress'] = false;
this.setState(temp),()=>console.log('State updated', this.state)
}
But never gets state updated. Any help?
You have syntax errors in all of your approaches. Note that setState() has the following format:
setState(updater, callback)
where updater can either be a function or an object and where callback is a function.
Starting with your initial approach:
this.setState({
fetchInProgress: false
}),()=>console.log('State updated', this.state)
should instead be:
this.setState({
fetchInProgress: false
},()=>console.log('State updated', this.state))
The other code is correct until, again, you get to the setState() part:
this.setState(temp),()=>console.log('State updated', this.state)
should instead be:
this.setState(temp,()=>console.log('State updated', this.state))

Page load errors due to missing this.setState

I'm getting an error when I populate my form with stored data. My form contains an array so I'm using {this.state.careerHistoryPositions.map((careerHistoryPosition) to create a loop. The error comes from {careerHistoryPosition.errors['company']. This part of the form, is related to errors when the form is submited and I don't store this in the database so when the form is populated, errors isn't set. I assume it's to do with this.setState looking for something that doesn't exist.
Snippet: Constructor
constructor(props) {
super(props);
let uniqueId = moment().valueOf();
const profileCandidateCollection = props.profileCandidate;
const profileCandidateCollectionId = profileCandidateCollection._id;
const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions;
this.state = {
careerHistoryPositions: careerHistoryPositions || [
{
company: '',
uniqueId: uniqueId,
title: '',
description: '',
startDateMonth: '',
startDateYear: '',
startDateMonth: '',
endDateYear: '',
isCurrent: false,
isDisabled: false,
errors: {}
}
],
profileCandidateCollectionId: profileCandidateCollectionId || null
};
}
Snippet: render
{this.state.careerHistoryPositions.map((careerHistoryPosition) => (
<div key={careerHistoryPosition.uniqueId} className="individual-position">
<SingleInput xs={9} inputType={'text'} controlFunc={this.handleCompanyNameChange(careerHistoryPosition.uniqueId)} content={careerHistoryPosition.company} placeholder={'Company'} bsSize={null}/>
{careerHistoryPosition.errors['company']
? <Col sm={12} className="has-error">
<span className="help-block custom-error">{careerHistoryPosition.errors['company']}</span>
</Col>
: ''}
</div>
))}

Resources