How do I post new data directly into a nested array in my json data file?

18 views Asked by At

I tried setting the endpoint of the POST request to 'http://localhost:3001/profiles/:id/logs' but I got this error: Failed to load resource: the server responded with a status of 404 (Not Found).

I have attached App.js file (containing all my routes), PetPage.js file (add/display logs specific to profile id), and db.json file (outlining the structure of my data).

App.js ,

PetPage.js ,

db.json

Also below is my AddPet.js file which successfully posts a new pet and its data:

    const [formData, setFormData] = useState({
        name: '',
        age: '',
        gender: '',
        breed: '',
        condition: '',
        vetName: '',
        vetNumber: ''
    });

    const handleChange = (e) => {
        const { name, value } = e.target;
        setFormData({
            ...formData,
            [name]: value
        });
    }
  


   const handleAddPet = (e) => {
    e.preventDefault();
    
    const lastProfile = profiles[profiles.length - 1];
    const newPetId = lastProfile ? lastProfile.id + 1 : 1; // Generate a new ID

    const newPetData = {
        id: newPetId, // Generate a new ID for the new pet
        name: formData.name,
        age: formData.age,
        gender: formData.gender,
        breed: formData.breed,
        condition: formData.condition,
        vetName: formData.vetName,
        vetNumber: formData.vetNumber,
        logs: [] // Empty logs for the new pet
    };

    fetch(`http://localhost:3001/profiles`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(newPetData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Failed to add pet');
        }
        return response.json();
    })
      .then(newPetData => {
        updateProfiles(newPetData)
        setFormData({
            name: '',
            age: '',
            breed: '',
            condition: '',
            gender: '',
            vetName: '',
            vetNumber: ''
        });
        alert('Pet added successfully!');
    })
    .catch(error => {
        console.error(error);
        alert('Failed to add pet');
    });
}

Here is my latest attempt:

import React, { useState } from 'react';
import { useParams, useHistory } from 'react-router-dom';

function AddLog({ profiles, updateProfiles }) {
  const [formData, setFormData] = useState({
    date: '',
    foodIntake: '',
    waterIntake: '',
    weight: '',
    notes: ''
  });

  const { id } = useParams();
  const history = useHistory();
  const profile = profiles.find(profile => profile.id === parseInt(id));

  if (!profile) {
    history.push('/');
    return null;
  }

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleAddLog = (e) => {
    e.preventDefault();

    const newLogData = {
      date: formData.date,
      foodIntake: parseInt(formData.foodIntake),
      waterIntake: parseInt(formData.waterIntake),
      weight: parseFloat(formData.weight),
      notes: formData.notes
    };

    fetch(`http://localhost:3001/profiles/${id}/logs`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(newLogData)
    })
    .then(response => {
      if (!response.ok) {
        throw new Error('Error adding log');
      }
      return response.json();
    })
    .then(data => {
      updateProfiles(data);
      setFormData({
        date: '',
        foodIntake: '',
        waterIntake: '',
        weight: '',
        notes: ''
      });
      history.push(`/profiles/${id}`);
    })
    .catch(error => {
      console.error('Error adding log:', error);
    });
  };

  return (
    <div>
      <h2>Add Log</h2>
      <form onSubmit={handleAddLog}>
        <label>Date:</label>
        <input type="date" name="date" value={formData.date} onChange={handleChange} required />
        <label>Food Intake:</label>
        <input type="number" name="foodIntake" value={formData.foodIntake} onChange={handleChange} required />
        <label>Water Intake:</label>
        <input type="number" name="waterIntake" value={formData.waterIntake} onChange={handleChange} required />
        <label>Weight:</label>
        <input type="number" name="weight" value={formData.weight} onChange={handleChange} required />
        <label>Notes:</label>
        <textarea name="notes" value={formData.notes} onChange={handleChange} required />
        <button type="submit">Add Log</button>
      </form>
    </div>
  );
}

export default AddLog;

Please message me if you need any more context surrounding my issue! :)

0

There are 0 answers