简体   繁体   中英

fetch() delete method in react hooks (with context api)

I have problem with delete item from json server. Rigth now I have a component where I stateless func component I generate li's with item from api. In another compinent I have a form, where I can add data. All works fine, till I try to delete items... The idea id to remove item after clicking (the method is on li). The weird part is, that after clicking, nothing is happening, but after refreshing the page clicked item is gone... I've als tried to use filter method, but it didn't help. In this 'app' I'm using context api to manage state. Code:

import React, { useContext, useEffect } from 'react';
import { MovieContext } from '../contexts/MovieContext';

const MovieList = () => {
  const { movies, setMovie } = useContext(MovieContext);

  const handleDelete = e => {
    const saved = e;
    fetch(
      `http://localhost:3004/movies/${e.target.id}`,
      {
        method: 'DELETE'
      },
      e.persist()
    )
      .then(m => m.json())
      .then(() => movies.filter(movie => movie.id === saved.target.id))
      .then(() => console.log(movies));
  };

  useEffect(() => {
    console.log(movies);
  });

  return (
    <div>
      <ul>
        {movies.map(movie => (
          <li id={movie.id} key={movie.id} onClick={handleDelete}>
            {movie.title}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default MovieList;

thanks for any help!

Array.filter does not modify the original array; it returns a new one with the filtered elements removed. Even if it did, with React, modifying the original array doesn't change the state, you need to call the setter and pass it a new object. So you want to do setMovie(movies.filter(movie => movie.id === saved.target.id))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM