I’m creating an update function with React:
function Company(props) {
const { contact, company, companies, setCompanies } = props;
const [isEditing, setIsEditing] = useState(false);
const [editedName, setEditedName] = useState(company.company_name);
const [editedAddress, setEditedAddress] = useState(company.company_address);
async function deleteCompany() {
const response = await fetch(`http://localhost/api/contacts/${contact.id}/companies/${company.company_id}`, {
method: 'DELETE'
});
if (response.ok) {
let newCompanies = companies.filter(c => c.company_id !== company.company_id);
setCompanies(newCompanies); // Update companies list
}
}
async function updateCompany(e) {
e.preventDefault();
const response = await fetch(`http://localhost/api/contacts/${contact.id}/companies/${company.company_id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
company_name: editedName,
company_address: editedAddress
})
});
if (response.ok) {
const updatedCompany = await response.json();
// Update the company in the companies array
const updatedCompanies = companies.map(c =>
c.company_id === updatedCompany.company_id ? updatedCompany : c
);
setCompanies(updatedCompanies); // Trigger re-render by updating state
setIsEditing(false); // Exit editing mode
}
}
and the way it return:
return (
<tr>
{isEditing ? (
<>
<td>
<input
type="text"
value={editedName}
onChange={(e) => setEditedName(e.target.value)}
/>
</td>
<td>
<input
type="text"
value={editedAddress}
onChange={(e) => setEditedAddress(e.target.value)}
/>
</td>
<td>
<button className="button green" onClick={updateCompany}>Save</button>
<button className="button red" onClick={() => setIsEditing(false)}>Cancel</button>
</td>
</>
) : (
<>
<td>{company.company_name}</td>
<td>{company.company_address}</td>
<td>
<button className="button green" onClick={() => setIsEditing(true)}>Edit</button>
<button className="button red" onClick={deleteCompany}>Delete</button>
</td>
</>
)}
</tr>
);
}
What I trying to do is that, when I update, the new data will immediately show up, but it did not. It only shows up when I refresh the page. This only happens with updateCompany()
, deleteCompany()
works well (the company data disappears right away when I click on delete button).
2
Answers
Make sure that your updateCompany function is correctly handling the server response.Your logic for updating the companies state looks good but make sure that companies is initialised correctly in the parent component. I’m adding console logs so that can help debug the values.
Added console logging for debugging. If the issue is still there try reviewing how API responds to the PUT request.
You need to check following on your
updateCompany
function:response.ok
is actually triggeredupdatedCompany
actually returns something,updatedCompanies
gives right result,setError
to right error from backendAs a bonus, it is always good to use
try/catch
.