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 1 year ago.
Improve this question
I am new to react. And I'm having problem understanding why cannot we access a state variable from document.addEventListener in class component?
And if that is possible how it is possible?
I'm not sure what you mean. You can both access and set state in a callback from addEventListener:
class Example extends React.Component {
state = {
clickCount: 0,
}
componentDidMount() {
document.addEventListener('click', () => {
console.log('old clicks', this.state.clickCount);
this.setState(prev => ({
clickCount: prev.clickCount + 1,
}));
});
}
// ...
}
Related
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 1 year ago.
Improve this question
I am creating my custom component, suppose api response is late(here I reproduced problem with setTimeOut()), then my ngModel is not updating until I select that component, I am using ChangedetectionStratagy OnPush
Here I am attaching stackblitz link directly . Please help
https://stackblitz.com/edit/primeng-dropdown-demo-2t9ed3?file=src/single-select/single-select.component.ts
It is working fine when I am making ChangedetectionStratagy.Default
Well since you are using onPush change detection strategy you have to trigger the change detection manually . with onPush the change detection is not trigger until component input changes. here is how you trigger it manually in your AppComponent
export class AppComponent implements OnInit {
constructor(private cf: ChangeDetectorRef) {} // insert changeDetectorRef
ngOnInit() {
setTimeout(() => {
this.selectedModel = 'CN';
this.cf.markForCheck() // line added
}, 2000);
}
https://stackblitz.com/edit/primeng-dropdown-demo-jbzchf?file=src/single-select/single-select.component.html
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 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 2 years ago.
Improve this question
I have to do drag and drop tree view using react-sortable-tree. And also I need crud operations in my tree view. I have done to add, edit and delete into my parent node on tree view. Unexpectedly, I have some issues whenever I drag my node that time my first-child will edit and after that updated properly, but could not work delete functions, and also nth-child will not work properly to add, edit and delete node.
My code sandbox live link.
The problem is you are updating the state using old setState syntax. Like this,
setState({ stateKey: stateValue });
But new useState hook doesn't need the stateKey. You can update the state by just calling the setState(stateValue).
So, instead of writing this,
settreeData({
treeData: removeNodeAtPath({
treeData: treeData,
path: path,
getNodeKey: ({ treeIndex: number, node: TreeNode }) => {
return number;
},
ignoreCollapsed: false
})
});
You should write this,
settreeData(
removeNodeAtPath({
treeData: treeData,
path: path,
getNodeKey: ({ treeIndex: number, node: TreeNode }) => {
return number;
},
ignoreCollapsed: false
})
);
Here is the working code link.
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
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 4 years ago.
Improve this question
So I feel like there is something small here that im missing, but don't really know what.
constructor(props) {
super();
this.state = {
developers: [],
};
}
componentDidMount() {
fetch('API').then(features => {
return features.json();
}).then(data => {
let developers = data.features.map((info) => {
let developer_info = info.properties.name
return(
<div key={info.id}>
{info.properties.name}
{info.properties.skills}
</div>
)
})
this.setState({ developers: developers});
console.log("state", this.state.developers)
console.log(this.props)
})
}
I would ideally like to call
this.state.developers.name
or this.state.developers.skills
as i need this information, but currently i am only able to save one property in the this.state or i can call out each thing. as i have done above, but its not useful, bc i can't put the info where i need it.
what am i doing wrong?
As a rule of thumb, in state you only want to store "serialisable" data. In general this means you should not store functions or recursive data structures.
A good way to check if your data is serialisable is to think if you could (or attempt to) use JSON.stringify() on it.
What you are storing here is almost certainly not serialisable, as you are storing to state complete React elements. A React element is the thing that is returned when you do <Component /> (which is the same as React.createElement(Component, ...).
So, in your case, what you should do is
let developers = data.features.map((info) => {
const developer_info = {
name: info.properties.name,
skills: info.properties.skills
}
return developer_info;
});
this.setState({ developers: developers});
So now you would have an array of plain Javascript objects in your state.
Access the updated state in callback of setState:
this.setState({ developers }, () => console.log("state", this.state.developers));
You should also store the data in state instead of the component view code (the html tags).
Access this.state.developers's properties in the component view code instead.