
I am very new to React and I can not solve this issue for a very long time. The idea is the following, I get some user info from database and pass it into cookies. From react side I get this cookies as JSON object and I need to render menu for user depending on values in this object. Right now I pass this object that I get from cookies from parent Component and I try to access it from Settings component. The issue is that I can see access this object from test function, however when I try to access this data from return it gives me undefined error. The function that returns value from cookies is sync, I have no idea why that might happen, please help.....
2 Answers
- Since
this.state.shopSettings["new_orders"]is boolean, use ternary. - Don't copy props to the state inside constructor as the constructor is executed only once. So updates to the props won't be reflected in the component.
Like this
<button onClick={this.test}>
{props.shopSettings && (props.shopSettings["new_orders"] ? 'true button' : 'false button')}
</button>
5 Comments
bredart
Unfortunately did not help, it seems that this code overloaded my computer and browser, it became very laggy. Dont know why that happened. I get them as object for 100% since I use Cookies.getJSON
Guru Hadadi
ok - try
{this.state.shopSettings && this.state.shopSettings)["new_orders"]} in the <button> ... if it doesn't work , then share the output of console.log ... also share more code if possiblebredart
Did not work, I have attached output of console.log(this.state.shopSettings) inside render. Also if try console.log(this.state.shopSettings['new_orders']) I get undefined
bredart
Also send project structure and component which gives this variable
bredart
This works as expected! Thank you, but is it possible to access this variables somehow? I will need to change them if user clicks on a button and so on, maybe there is better solution than cookies? I can build an api but I have questions about authentications, I run everything using next and koa right now
It solves very easily with this code, now I can access any key from shopSettings inside return without any issues
class Index extends React.Component {
state = {
shopSettings: Cookies.getJSON('shopSettings')
}
render() {
const {shopSettings} = this.state
if (!shopSettings) {
return null
}
return (
<div>Hello</div>
)
}
testfunction you are accesingthis.state.shopSettingwhereas in your component, you are accessingthis.state.shopSettings(with an extra S at the end). What's weird is thattestshould log undefined.this.state.shopSettingsif you console.log it in therender()function? It's possible that 'new_orders' key does not exist in the object.