javascriptreactjsimdb

Adding duplicates into array


I would like to be able to sort my array so I don't have duplicates into my "Recently-Viewed" section. The recently viewed section works fine except that it breaks when I add a duplicate. So I want to be able to sort my array so it doesn't break. I'm not really sure how to implement a sort function. Do I use filter or what do I do? I'm really confused.

picture of problem

My code:

const [tvShow, setTVShow] = useState([]);
const [recentlyViewed, setRecentlyViewed] = useState([]);

const getMovieRequest = async () => {
    const url = `https://api.themoviedb.org/3/movie/top_rated?api_key=1e08baad3bc3eca3efdd54a0c80111b9&language=en-US&page=1`;
    
    const response = await fetch(url);
    const responseJson = await response.json();

    setTVShow(responseJson.results)

};

useEffect(() => {
    getMovieRequest();
},[]);

useEffect(() => {
    const recentlyMovies = JSON.parse(localStorage.getItem('react-movie-app-favourites')
    );
    
    if (recentlyMovies) {
        setRecentlyViewed(recentlyMovies.slice(0,5));
    }
}, []);

const saveToLocalStorage = (items) => {
    localStorage.setItem('react-movie-app-favourites', JSON.stringify(items))
};

const addRecentlyViewed = (movie) => {
    const newRecentlyViewed = [movie, ...recentlyViewed]
    setRecentlyViewed(newRecentlyViewed.slice(0,5));
    saveToLocalStorage(newRecentlyViewed);

    if (newRecentlyViewed > 5) {
        newRecentlyViewed.pop();
    }
};

Thank you guys in advance. I'm new to React and I find this very confusing.


Solution

  • Using the Set constructor and the spread syntax:

    uniq = [...new Set(array)];
    
     useEffect(() => {
            const recentlyMovies = [...new Set(JSON.parse(localStorage.getItem('react-movie-app-favourites')))];
            
            if (recentlyMovies) {
                setRecentlyViewed(recentlyMovies.slice(0,5));
            }
        }, []);