Why does the POST stop working when trying to set State using useEffect and fetch?
In this first example, I can see in the POST log in the Chrome console and print in Flask:
React:
import React, { useEffect, useState } from "react";
import Button from '@mui/material/Button';
import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward';
import TextField from '@mui/material/TextField';
export default function Heater(props) {
const [status, setStatus] = useState({
"id": props.id,
"name": props.name,
"pin": props.pin,
"setpoint": 1
});
function incrementSetpoint() {
setStatus(previousValue => {
return {
...previousValue,
"setpoint": status.setpoint + 1
};
});
};
useEffect(() => {
fetch('/heaters', {
method: 'POST',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify(status)
})
.then((response) => response.json())
.then((response) => console.log(response))
.catch((error) => (console.error(error)))
});
return (
<div>
<h1>{ props.name }</h1>
<div className="inputs-container" style={{ marginBottom: '2ch' }}>
<TextField label="Setpoint" value={ status.setpoint } />
<Button variant="contained" onClick={ incrementSetpoint }>
<ArrowUpwardIcon></ArrowUpwardIcon>
</Button>
</div>
</div>
);
}
Flask:
from flask import jsonify
@app.route('/heaters', methods=['GET', 'POST'])
def heaters():
"""Control heaters and return the current heater configuration."""
if request.method == 'POST':
print(request.json)
return jsonify(request.json)
Now, if I comment out the console.log and use setState instead, it causes and infinite loop in Flask.
...
useEffect(() => {
fetch('/heaters', {
method: 'POST',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify(status)
})
.then((response) => response.json())
// .then((response) => console.log(response))
.then((response) => setStatus(response)) // New line here
.catch((error) => (console.error(error)))
});
...
After reading some other posts, I decided to add an empty array to useEffect. This stops the infinite loop. I can see that setStatus is working by adding console.log(status). However, the POST is no longer working.
...
useEffect(() => {
fetch('/heaters', {
method: 'POST',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify(status)
})
.then((response) => response.json())
// .then((response) => console.log(response))
.then((response) => setStatus(response)) // New line here
.catch((error) => (console.error(error)))
}, []); // Empty array added here
console.log(status); // New line here to confirm setStatus works
...
On the initial startup, I can see the POST log in the Chrome console and print in Flask. After it has loaded, the POST does not work. Any ideas on what is causing the issue?