Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I want to change a value in the parent component by changing the state in the child component which is passed by props.
// This is the parent component
const [showEdit, setShowEdit] = useState(false);
<EditApplicationSettings
appSettings={appSettings}
changeState={(showEdit) => setShowEdit(showEdit)}
/>
// This is the child component
export default function EditApplicationSettings({ appSettings, props }) {
return (
<button
className="button-red"
onClick={() => props.changeState(false)}
>
Cancel
</button>
);
}
When I click on the button, that should change the state in parent, but instead, I get an error.
TypeError: Cannot read properties of undefined (reading 'changeState')
Where did I do wrong in passing the props?
In React terms props tends to refer to the entire property object:
EditApplicationSettings(props)
But since you're destructuring the properties from the object you need to reference the changeState property explicitly:
EditApplicationSettings({ appSettings, changeState })
and
onClick={() => changeState(false)}
To solve this error
TypeError: Cannot read properties of undefined (reading 'changeState')
then this line
export default function EditApplicationSettings({ appSettings, props }) {
should be
export default function EditApplicationSettings({ appSettings, ...props }) {
^^^
You could read more at MDN doc for destructuring assignment
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I have a component which called <Header> and another component <AboutMe>, I wanted to pick an element with an id from <AboutMe> and add an event listener onClick.
the thing is whenever i try to use getElementById it returns the element which I wanted but when I try to add the event listener...throws an error.
Related to your title of this question:
You can achieve the passing of data and objects through to child components through the use of attributes where you use your component.
You really don't need to use the DOM to access the elements on the page, and with React being highly dynamic in nature, the DOM is in a constant state of change which can lead to many issues if you try to bypass React.
So if you have your header component used in your app like this...
<PageHeader userData={ userData } />
Then within your component, which is named PageHeader in this example, define the constants as:
const PageHeader = (props) => {
const userData= props.userData;
Note the object name to use with "props" is the same that you used with the attribute name.
Props will contain all attributes that are defined on the attribute where the component is used.
Just to provide another way to use "props" (the name is not significant) I'll include this code snippet too. Notice that react will auto map each one to it's proper constant... which is pretty cool.
const PageHeader = ( props ) => {
const { uischema, schema, path, visible, renderers, userData } = props;
And one last thing that I should mention, is the use of the props.children, which can be very useful too. This is where DivScrollable is defined, and is using the props.children.
const DivScrollable = (props) => {
return (
<div className={styles.divscrollable} >
{props.children}
</div>
);
};
So the power of props.children is that it passes along the contents of what is contained between the opening and closing tags of a component. In this example it's the MyComponent object that is within the props.children object. But it could also include others too since it's "all of the content" between the component tags.
<DivScrollable>
<MyComponent src={props.src}
theme="monotyped"
spacing="4"
enableClipboard="true"
name={null}
/>
</DivScrollable>
To then address the onClick handling, which you mention within the body of your question, you can use use it like the following, where I am reusing the above examples... see the "onClick" addition within the DivScrollable component.
const DivScrollable = (props) => {
const performSomeFunction= (aValue) => {
... code goes here...;
};
return (
<div className={styles.divscrollable}
onClick={() => {
performSomeFunction(true);
}} >
{props.children}
</div>
);
};
I am not sure why you mentioned Header component, but did you try like this?
function clickEvent() {
...
}
const el = document.getElementById("element_id");
el.addEventListener("click", clickEvent, false);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
I have a computed property based on some nested object properties. When the object gets changed, the computed property seems to update (In vue-dev-tools) but the change is not reflected in the UI. I'm aware of nested object reactivity, but I never change/assign a nested property of my order object, the only time it changes is in the updateOrder() (which assigns the object at the root level.
Is there a reason why my UI isn't updating? Are the dev tools synced to the sames state as the UI is? Am I missing something about Vue's reactivity system?
Here is some very simplified code:
<template>
<my-component
#order-changed="updateOrder"
/>
<div v-if="isOrderComplete">
Your order is complete // this never shows until I refresh page
</div>
<div v-else>
Please Submit the order // this shows at first
</div>
</template>
export default {
props: function(){
initialOrder: Object,
},
data: function(){
order: this.initialOrder
},
methods: {
updateOrder: function(newOrder){ // gets triggered by a child component
this.order = newOrder;
}
},
computed: {
isOrderComplete: function(){ // starts as false, becomes true later, seems to be updated in dev-tools
return this.order.foo || this.order.bar
}
}
}
Nested objects does not automatically update computed properties, you can watch for changes in the Watch property.
watch: {
'order.foo'(newValue) {
// * If any changes happed, this will be triggered !
}
}
TLDR: Make sure you don't have any javascript errors in the console
I could not reproduce the error in an isolated codepen. So I figured something else was going on. I had some errors being thrown from a side effect of updating my order. They seemed unrelated, but once I fixed all my errors, the bug went away. I think the error short-circuited the Vue lifecycle even if the error had nothing to do with my computed property.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 10 months ago.
Improve this question
here is my code and I cannot find where the problem is
import React, {Component} from "react";
export default class Product extends Component{
state = {
id: this.props.product.id,
productName: this.props.product.productName,
price: this.props.product.price,
}
render(){
return<div className="col-lg-g">
<div className="card m-2">
<div className="card-body">
<div className="text-muted"># {this.props.id}</div>
<h5 className="p-5 border-top">{this.props.productName}</h5>
<div>$ {this.props.price}</div>
//{console.log(state)}
</div>
</div>
</div>
}
}
it shows Line 17:36: 'state' is not defined no-undef
whenever I run the code
That's a class, when you write state = ... , that's an instance property, hence you access it with this.state.
ok i did console.log(state) but i should have used console.log(this.state)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I have fetched the array using the graphql query and stored it in a variable called mpbrands. Now I want to store it in the state and render it in my component. I tried the below but its not giving any response
constructor(props) {
super(props)
this.state = {
count: 0
}
}
async componentDidMount(){
let brandQuery = BrandPageInstance.getBrandList();
await fetchQuery(brandQuery).then((mpbrand) => {
this.setState({
count: mpbrand.items
})
console.log(count)
},
(error) => console.log(error)
)
}
In the console I am getting an error Uncaught (in promise) ReferenceError: count is not defined . My array structure is
mpbrand:
items: Array(10)
0: {default_value: "CHEVROLET", image: "image_url"}
Let me know how to do it. Since I am newbie not able to store it in the state
Try console.log(this.state.count) That should solve the reference error.
count is part of the state object. So you can access it via this.state.count.
First of all count is not your state. It's the property state.
Secondly, replacing console.log(count) with console.log(this.state.count) won't work (in the essence that you won't see count updated) since your new state will only be available to you in next render.
But setState provides a second callback where you can access the updated state like so :-
this.setState({
count: mpbrand.items
},()=>console.log(this.state.count))
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have an object as a state with some properties. I want to update the state in a condition with a hook.
But it causes an infinite loop.
Can I update the state directly like this?
const [info, setInfo] = useState({name: '' })
if (info.name === '') {
info.name = 'empty'
}
Is this ok to do?
you should use useState as said in the following way:
const [info, setInfo] = useState({name: '' })
if (info.name === '') {
setInfo({...info, name = 'empty'});
}
this will set info with only the change of the name property
A hook is something that starts with use like useState. setState is not a hook - it's a setter/updater. It can be used inside of a conditional statement. If it's done properly there shouldn't be any infinite loops.
In React Functional Components, useState hook is used as an alternate to state in class components. The correct way to use the useState hook is
const [ variable, setVariable ] = React.useState( //default value );
The default value can be null, " string ", { object } , true / false, or 0, 1, 2 .......
And just like this.setState() in class components, you set the state with the
setVariable( newValue );
Never ever try to change the state variables like you change the normal variables. They are immutable for one render and hence cause re-render when called setState.
And for the infinite loop, please copy paste your component