I'll preface this by stating that I'm a complete beginner at React.js
I've created an example of a project I'm working on where I call an API in componentDidMount() and get an array of objects back, setting it in state. Here's what it looks like:
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
thing: []
}
}
componentDidMount() {
// Fake API
const apiCall = () => ({
data: "test"
})
// Fake call
const data = apiCall()
this.setState({
thing: [
...this.state.thing,
data
]
})
}
render() {
return (
<div>
<h1>{ this.state.thing[0].data }</h1>
</div>
)
}
}
I'm aware that setState isn't guaranteed to update when it's used according to the documentation. I also found "forceUpdate()," and the docs recommends using it as little as possible. Nevertheless, I attempted to use it, but to no avail.
I'm able to console.log the new state during the componentDidMount() run and in the render's h1 element, but I'm unable to actually show it in the render since it's rendering an empty state array at first.
My question is:
Is there a way to force my state to update before the render is run by my program so that I can see it, and if not, how would I be able to see my new state reflected in the JSX?