Reputation: 131
I have my API set up in Spring boot and when you call one of the methods it returns a string of either success or fail. However my fetch consoles out success but when I try to save it to a variable it says undefined. How can I get that success or fail string from my API?
handleSubmit(event) {
var a ;
event.preventDefault();
this.setState({username:'poop'})
console.log("submit");
fetch('http://localhost:8080/login/'+this.state.username+'/'+this.state.password,{
method: 'GET',
}).then((resp)=> resp.text())
.then(function(data){
a= data;
})
Upvotes: 1
Views: 476
Reputation: 5854
I hope you send response as json. if yes then please use .then((resp)=> resp.json()). Please check below complete example for calling api using fetch.
import React, {Component} from "react";
class FetchExample extends React.Component {
state = {
isLoading: false,
questions: [],
error: null
};
async fetchQuestions(){
fetch(`https://opentdb.com/api.php?amount=10&difficulty=hard&type=boolean`,)
.then(response => {
if (response.status !== 200) {
console.log('There was a problem. Status Code: ' + response.status);
return;
}
response.json().then(data => {
console.log(data);
this.setState({
questions: data,
isLoading: false
})
});
}
)
.catch(function (error) {
console.log('Error: ', error);
this.setState({error, isLoading: false})
});
};
render() {
const {isLoading, questions, error} = this.state;
return (
<React.Fragment>
<h1>Random Question</h1>
<button onClick={this.fetchQuestions}>Click for calling API using fetch</button>
{error ? <p>{error.message}</p> : null}
{!isLoading && questions.results ? (
questions.results.map((questions, index) => { //something right here
//is erroring
const {question, category, type, difficulty} = questions;
return (
<div key={index}>
<p>Question: {question}</p>
<p>Question Type: {type}</p>
<p>Difficulty: {difficulty}</p>
<hr/>
</div>
);
})
) : isLoading ? (
<h3>Loading...</h3>
) : null}
</React.Fragment>
);
}
}
export default FetchExample;
Upvotes: 1