I have a simple react component and express endpoint that returns the string "sample data". I'm just trying to hit that endpoint in my react app and store the text in state and display it on the screen.
My component:
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
this.callBackendAPI()
.then(res => this.setState({ data: res.data }))
.catch(err => console.log(err));
}
async callBackendAPI() {
const response = await fetch('/sampleData');
const body = await response.json();
if(response.status !== 200) {
throw Error(body.message)
}
return body;
}
render() {
let data = this.state.data || 'there is no data';
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">{data}</p>
</div>
);
}
}
export default (App);
The backend endpoint:
app.get('/sampleData', function(req, res) {
res.send('sample data');
});
I'm not sure I need response.json() since the endpoint just returns plain text, I actually get an error with this code SyntaxError: Unexpected token s in JSON at position 0. When I just use response nothing happens and the text just shows up as "there is no data" since the state is empty.
How can I get the text from my endpoint into the components state and displayed on screen?
Thanks!