In my ReactJS frontend I am building a form where the user can view and edit settings. The form is part of a function that does the following:
- Call the backend to get the settigs. Store the result from backend in variable
data - Map/show the
datain text fields - When the user clicks "Submit" then send changes as json back to the backend.
This is a picture of the flow:
This is a picture of the ReactApp:
This is my code so far:
import { useContext, useEffect, useState } from "react";
export function Settings() {
const [data, setData] = useState([]);
// Send general settings
const handleSubmit = async (e) => {
e.preventDefault();
let result = await fetch("https://localhost:5002/api/update_settings", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: data,
});
let resultJson = await result.json();
let resultMessage = resultJson['message']
let resulData = resultJson['data']
let resultError = resultJson['error']
if (result.status === 200 || result.status === 201) {
document.getElementById("feedback_div").style.display = "block";
document.getElementById("feedback_p").innerHTML = resultMessage;
}
else{
document.getElementById("feedback_div").style.display = "block";
document.getElementById("feedback_p").innerHTML = resultError + " " + resultMessage;
}
};
useEffect(() => {
fetch('https://localhost:5002/api/get_settings')
.then(response => response.json())
.then(json => setData(json))
}, []);
return (
<div>
<h1>Settings</h1>
{/* Feedback */}
<div id="feedback_div" style={{display: "none"}}><p id='feedback_p'>Feedback box is here</p></div>
{/* Form */}
<form onSubmit={handleSubmit}>
<label>
<p>Title</p>
<input type="text" name="inp_title" value={data?.settings_website_title} onChange={(e) => setData(e.target.value)} />
</label>
<label>
<p>Title short</p>
<input type="text" name="inp_title_short" value={data?.settings_website_title_short} onChange={(e) => setData(e.target.value)} />
</label>
<p><button>Submit</button></p>
</form>
</div>
);
}
export default Settings;
Backend get_settings return value:
{
"settings_website_title", "My Website",
"settings_website_title_short", "MyWeb"
}
My problems:
How can I send the data back to the backend? I belive that when the user makes changes into the text box I call onChange={(e) => setData(e.target.value)} but I do not think this is correct? Because data should be the JSON, and not a single value.
Also I get this error on this code:
Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components

