I'm creating a React component that will be displayed on the landing page. The component will display a string from the back office. If the string contains a specific chain, like #age#
, this would trigger an ajax request to get the user's age, and then replace #age#
by it.
My issue is that even though I can access my string, and it works with a string I created myself for some tests, it doesn't work when I work with this.state
, saying it's undefined. I also can't make it work with any function whatsoever.
Here is how I do this so far:
import React from 'react';
export default class homeLanding extends React.Component {
state = {
settings_data: [],
user_data: [],
};
componentDidMount() {
if(localStorage.getItem('settings_data') === null) {
$.ajax({
url: '/settings',
method: 'GET',
dataType: 'json',
success: function(data){
self.setState({settings_data: data});
localStorage.setItem('settings_data', JSON.stringify(data));
}
});
}
else {
this.setState({settings_data: JSON.parse(localStorage.getItem('settings_data'))});
}
}
render() {
let welcome_title = this.state.settings_data.welcome_title;
// returns "welcome to site"
if(welcome_title.includes('site')) {
console.log('yaaaaaaay');
} // error, cannot read includes of undefined
return (
<div className="col-md-10 main">
<h1>{this.state.settings_data.welcome_title}</h1>
<!-- Displays correctly the title -->
</div>
)
}
}
My question is the following: why doesn't it work, and how can I make it so? Am I missing anything?