skip to Main Content

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


  1. 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.

    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();
            console.log('Updated company data:', updatedCompany);
    
            // Update the company in the companies array
            const updatedCompanies = companies.map(c =>
                c.company_id === updatedCompany.company_id ? updatedCompany : c
            );
            console.log('Updated companies list:', updatedCompanies); 
    
            setCompanies(updatedCompanies); 
            setIsEditing(false); 
        } else {
            console.error('Failed to update company:', response.statusText);
        }
    }

    Added console logging for debugging. If the issue is still there try reviewing how API responds to the PUT request.

    Login or Signup to reply.
  2. You need to check following on your updateCompany function:

    1. if response.ok is actually triggered
    2. if updatedCompany actually returns something,
    3. if updatedCompanies gives right result,
    4. else setError to right error from backend
    async function updateCompany(e) {
        e.preventDefault();
    
        try {
            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) {
                throw new Error(`Failed to update company: ${response.status} ${response.statusText}`);
            }
    
            const updatedCompany = await response.json();
    
            if (!updatedCompany || !updatedCompany.company_id) {
                throw new Error('Invalid data received from server');
            }
    
            // Update the company in the state
            const updatedCompanies = companies.map((c) =>
                c.company_id === updatedCompany.company_id ? updatedCompany : c
            );
            setCompanies(updatedCompanies); 
            setIsEditing(false); 
    
        } catch (error) {
            console.error('Error updating company:', error);
            alert(`An error occurred while updating the company: ${error.message}`);
        }
    }
    

    As a bonus, it is always good to use try/catch.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search