`getDerivedStateFromProps` is not updating the state - reactjs

I am trying to update the state of class component via props that sent from above component,
At first I've set an constructor that fetch the data from the props and place it in the state but that did not work because of the render() did not called.
So I've reed of the function getDerivedStateFromProps which called before render, But I don't know if I'm using it correct.
I'm send an prop as institute from above component and implement the getDerivedStateFromProps() like this:
static getDerivedStateFromProps(nextProps, prevState) {
if (prevState.id !== nextProps.institute.id) { // need to update
return {
id: nextProps.id,
name: nextProps.name,
contactName: nextProps.contactName,
phoneNumber: nextProps.phoneNumber,
city: nextProps.city,
street: nextProps.street,
number: nextProps.number,
deleted: nextProps.deleted
};
}
console.log("null")
return null;
}
I've also set an initState values:
state = {
id: '',
name: '',
contactName: '',
phoneNumber: '',
city: '',
street: '',
number: '',
deleted: '',
}
getDerivedStateFromProps if statement is true but it's not updating the state at all.
I will appreciate any kind of help.
Thanks!

Related

React - override state by exists object properties

I have state with properties initialized with empty string, because im putting these into form inputs. Additionaly I get object from Firebase with properties matching with state but not every one exists. I would set state properties by properties of this object if properties exists.
Here is necessary example:
class App extends Component {
state = {
user: {
firstName: "",
lastName: "",
gender: "",
address: {
street: "",
city: "",
state: ""
}
}
}
componentDidMount(){
const newObjectFromFirebase = {
firstName: "Lucas",
address: {
city: "London"
}
}
this.setState(newObjectFromFirebase);
}
render() {
const stateJson = JSON.stringify(this.state);
return (
<div className="App">
{stateJson}
</div>
);
}
}
I would like to get state with override properties in only these properties which exists in object from firebase. Otherwise I would like to keep the previous state. Currently state properties are completely overwritten by new object.
Thats what I want:
user: {
firstName: "Lucas",
lastName: "",
gender: "",
address: {
street: "London",
city: "",
state: ""
}
}
Thats what I have:
user: {
firstName: "Lucas",
address: {
city: "London",
}
}
Any smart solution or library ?
You can just use the spread syntax ... like this:
const newObjectFromFirebase = {
firstName: "Lucas",
address: {
city: "London"
}
}
this.setState(prevState => {
user: {
...prevState.user,
...newObjectFromFirebase,
address: {
...prevState.user.address,
...newObjectFromFirebase.address
}
}
});
This will merge the 2 objects together and override the state.

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'">

How to do setState for an object inside constructor -> state?

How to do setState for {items.name} an object which is inside constructor -> this.state -> items: { name: '', age:'' }
Inside the constructor instead on doing setState you can assign value to this.state
this.state = {
name: "",
age: ""
}
But there is rarely a use case where in you need to do it this way.
If you need to set the state of bugDetail ,
in constructor you can do this:
constructor(props) {
super(props);
this.state = { bugTitle : '',
bugDescription : '',
bugType : '',
bugDetail : { title : '', description : '', type: '' },
bugDetailArray : [] } }
do the following later: ->
this.setState({bugDetail:{title:"updated",description : 'olderdesc', type:"older"}})
also can do:->
updateTitle(updatedTitle){
let newBugdetail = this.state.bugDetail;
newBugdetail.title = updatedTitle;
this.setState({bugDetail:newBugdetail })
}
else you need to keep the title as an outside key in the state
I believe that your constructor looks like this
constructor(props) {
super(props);
this.state = {
bugTitle : '',
bugDescription : '',
bugType : '',
bugDetail : {
title : '',
description : '',
type: ''
},
bugDetailArray : []
}
}
So in order to change the state using setState in your function
someFunction = (e) => {
let inputName = e.target.name;
let inputValue = e.target.value;
let updatedFormState = Object.assign({}, this.state);
updatedFormState.bugDetail["title"] = inputValue;
this.setState(updatedFormState);
}

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

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) => {}

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))

Resources