Issue
I'm using a button to call a function that is supposed to fetch data from my backend server hosted in Flask.
The react function passes information to flask and flask returns a JSON response. I have confirmed that Flask receives the necessary information and React receives the response from Flask by looking at the Network Response thing in Google chrome. However, I can't seem to access it.
I have tried to console.log
it but it does not seem to work. I expected something to print out but nothing does even though the request is being sent.
const fetchDataFromBackend = () => {
const filters = { age, class, username, };
fetch('/query', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(filters)
}).then(response => {
if (response.ok) {
console.log(response)
return response.json()
}
}).then(data => setTableData(data))
}
I know there are similar posts but none of the solutions I have seen have helped. Also, none of the ones I have read mention a button so I am a bit more confused. I have tried all sorts of things and nothing has really changed.
Solution
You're attempting to log the response and then parse it as JSON. But since response.json() is asynchronous and returns a Promise, you should handle the parsed data in another .then() block, which you're already doing correctly to update your component's state with setTableData(data). try it like this
const fetchDataFromBackend = () => {
const filters = { age, class, username };
fetch('/query', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(filters)
})
.then(response => {
if (response.ok) {
return response.json(); // parse JSON only if the response is ok
} else {
throw new Error('Network response was not ok.');
}
})
.then(data => {
console.log("Received data:", data); // log the parsed data
setTableData(data); // update state with the parsed data
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
};
Answered By - Adesoji Alu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.