I have a rest API back end set up. I want to set values inside the getInitialState
function for a component, but I can't figure out how to populate the object I need to return because I am using an asynchronous http request. The object I return has undefined values, as expected. How do I get around this?
I'm using fetch (can switch to any other library, honestly) as of now. I can't figure out how to call getInitialState
after the asynchronous call has returned some value instead of before it happens.
import React from 'react';
import 'whatwg-fetch';
export default class IndexPage extends React.Component {
render() {
// I basically need to call getInitialState after the last promise has been resolved
fetch('https://localhost:3000/api/aye')
.then(function(response) {
return response.json();
})
.then(function(json) {
// Need to return some values from this.
});
return (
<div>
<h1>{this.state.jsonReturnedValue}</h1>
</div>
);
}
}
Thanks in advance!
To set initial React state from API data, we can make the request in the useEffect callback. And we pass in an empty array as the 2nd argument to only make it run when the component mounts. We have the getAns function that makes a GET request with fetch . Then we call res.
There are two ways to initialize state in a React component: inside the constructor, and directly inside the class.
To make the state change, React gives us a setState function that allows us to update the value of the state. Calling setState automatically re-renders the entire component and all its child components. We don't need to manually re-render as seen previously using the renderContent function.
You should call this.setState
in order to change state
values
export default class IndexPage extends React.Component {
constructor() {
super();
this.state = {
jsonReturnedValue: null
}
}
componentDidMount() {
fetch('https://localhost:3000/api/aye')
.then(response => response.json())
.then(json => {
this.setState({ jsonReturnedValue: json });
});
}
render() {
return (
<div>
<h1>{ this.state.jsonReturnedValue }</h1>
</div>
);
}
}
In your situation -
It's better to get the rendering done for the first time with empty state data lets say
constructor(props){
super(props);
this.state = {
data : []
};
}
and make ajax call in componentDidMount
, this is the place where you can perform dom manipulation and send ajax
request to fetch data via REST
.
After new data is fetched from server set the state with new data
this.setState({data:newDataFromServer});
e.g In componentDidMount
componentDidMount() {
sendAjaxRequest()
.then(
(newDataFromServer) => {
this.setState({data : newDataFromServer });
});
}
This will cause the re-rendering to happen with latest data fetched from server and new state changes will be reflected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With