Home > other >  I'm trying to delete an object from an array and the response I get is that the data is undefin
I'm trying to delete an object from an array and the response I get is that the data is undefin

Time:05-02

Im new in coding and faceing some problems and need some help I would appreciate if someone could help me out with this. First Im using react.js for bilding my app and I made a fake rest api using npm json.server. Every step in the code is working but not the method DELETE and dont manage to remove the object from the array. In my VS terminal i get a 404 response like this DELETE /albums/undefined 404. So i think it's not managing to see the data in the array.

the delete method looks like this:

const onDelete = async (id) => {
    await fetch(`http://localhost:3500/albums/${id}`, {
      method: "DELETE",
    })
      .then((res) => {
        console.log(res.json);
        if (res.status !== 200) {
          return;
        } else {
          setUsers(
            albums &&
              albums.filter((album) => {
                return album.id !== id;
              })
          );
        }
      })
      .catch((err) => {
        console.log(err);
      });
    // console.log(data);
  };

Now I can post my complete function this is my function:

import "./App.css";
import AddUser from "./components/adduser/AddUser";
import User from "./components/users/User";

const App = () => {
  const [albums, setUsers] = useState([]);
  const [genres, setGen] = useState([]);
  useEffect(() => {
    fetchData();
    fetchGenres();
  }, []);

const fetchData = async () => {
    await fetch("http://localhost:3500/albums")
      .then((res) => {
        if (res.ok) {
          console.log("everthing is OK!");
        } else {
          console.log("Somethig went wrong");
        }
        return res;
      })
      .then((res) => res.json())
      .then((data) => setUsers(data))
      .catch((err) => {
        console.log(err);
      });
  };

const fetchGenres = async () => {
    await fetch("http://localhost:3500/genres")
      .then((res) => {
        if (res.ok) {
          console.log("everthing is OK!");
        } else {
          console.log("Somethig went wrong");
        }
        return res;
      })
      .then((res) => res.json())
      .then((value) => setGen(value))
      .catch((err) => {
        console.log(err);
      });
  };

const onAdd = async (name, band, city, genresId) => {
    await fetch("http://localhost:3500/albums", {
      method: "POST",
      body: JSON.stringify({
        name: name,
        band: band,
        city: city,
        genresId: parseInt(genresId),
      }),
      headers: {
        "content-type": "application/json;charset=UTF-8",
      },
    })
      .then((res) => {
        // console.log(res.method);
        if (res.status !== 201) {
          return;
        } else {
          return res.json();
        }
      })
      .then((data) => {
        setUsers((albums) => [data, ...albums]);
      })
      .catch((err) => {
        console.log(err);
      });
  };

const onDelete = async (id) => {
    await fetch(`http://localhost:3500/albums/${id}`, {
      method: "DELETE",
    })
      .then((res) => {
        console.log(res.json);
        if (res.status !== 200) {
          return;
        } else {
          setUsers(
            albums &&
              albums.filter((album) => {
                return album.id !== id;
              })
          );
          console.log(res.album);
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };

return (
    <div className="App">
      <h3>Bands Albums & Genres</h3>
      <br />
      <AddUser onAdd={onAdd} values={genres} />

      <div>
        {albums &&
          albums.map((album) => (
            <User
              name={album.name}
              band={album.band}
              city={album.city}
              genresId={
                genres &&
                genres.map((g) => {
                  if (g.id === album.genresId) {
                    return g.name;
                  }
                  return "";
                })
              }
              onDelete={onDelete}
            />
          ))}
      </div>
    </div>
  );

My array structure looks like this:

{
  "albums":[
   {
      "name": "albumName1",
      "band": "BandName1",
      "city": "City",
      "id": 0,
      "genresId": 0
    },
    {
      "name": "albumName2",
      "band": "BandName2",
      "city": "City",
      "id": 1,
      "genresId": 0
    },
    {
      "name": "albumName3",
      "band": "BandName3",
      "city": "City",
      "id": 2,
      "genresId": 3
    }
],
"genres": [
    {
      "id": 0,
      "name": "grunge"
    },
    {
      "id": 1,
      "name": "rock"
    },
    {
      "id": 2,
      "name": "jazz"
    },
    {
      "id": 3,
      "name": "pop"
    },
  ]
}

this is the component that I'm using for render:

const User = ({ id, name, band, city, genresId, onDelete }) => {
  const handleDelete = () => {
    onDelete(id);
  };

  return (
    <div className="list">
      <span>{name}</span>
      <span>{band}</span>
      <span>{city}</span>
      <span>{genresId}</span>

      <span>
        <button onClick={handleDelete}>delete</button>
      </span>
    </div>
  );
};

I have some more components in the function but I dont think that they have any influence in what i'm trying to accomplish.

CodePudding user response:

console log what is id from onDelete function and you will see that it is undefined. That's why endpoint /albums/undefined is called.

return (
    ...
    onDelete={onDelete} // the problem is here
    ...
);

further reading: https://reactjs.org/docs/faq-functions.html#how-do-i-pass-a-parameter-to-an-event-handler-or-callback

CodePudding user response:

You are getting an error because you are not passing id prop to the <User /> component.

Try this

           <User
              name={album.name}
              band={album.band}
              city={album.city}
              id={album.id}               <----- Add this line
              genresId={
                genres &&
                genres.map((g) => {
                  if (g.id === album.genresId) {
                    return g.name;
                  }
                  return "";
                })
              }
              onDelete={onDelete}
            />
  • Related