I have asked other questions in the past, but I received unhelpful answers. I am still looking for proper solutions.
Currently, I am retrieving an array from the backend using Redux.
const { movies, message } = useAppSelector(state => state.movies);
The object stored in state.movies
consists of two fields: movies
and message
. When I created the Redux reducers, I defined the types for these fields. Now, in the component, I'm accessing the data. The type for movies
is set as an array
since that's what I receive from the backend, while the type for message
is a string
.
To summarize, movies
is an array and message
is a string, both found within state.movies
.
My goal now is to filter this movies
-
const matches = movies.filter((movie: movie ) => {
const escapeRegExp = (str: string) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const regex = new RegExp(escapeRegExp(search), "gi");
return movie.name.match(regex);
})
However, I encounter an error that says-
Property 'filter' does not exist on type 'never'
.
I understand the issue here. TypeScript cannot determine that movies
is an array. I need to explicitly define or declare that the movies
field is an array. But how can I do that?
Below is the complete component structure-
import type { NextPage } from "next";
import { useState, useEffect } from "react";
import { Container } from "@mui/material";
import { GetServerSideProps } from "next";
//Redux
import { wrapper } from "Redux/Store";
import { getMovies } from "Redux/Action/movieAction";
import { useAppSelector } from "Redux/Hook";
//Components
import Search from "Components/Movies/Search";
import Lists from "Components/Movies/Lists";
type movie = {
name: string;
image: string;
releaseDate: string;
watchedDate: string;
}
const Movies: NextPage = () => {
const { movies, message } = useAppSelector(state => state.movies);
const [movieList, setMovieList] = useState<[]>(movies);
const [search, setSearch] = useState<string>("");
useEffect(() => {
let matches = []
if (search.length > 0) {
matches = movies.filter((movie: movie ) => {
const escapeRegExp = (str: string) => str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
const regex = new RegExp(escapeRegExp(search), "gi");
return movie.name.match(regex);
})
}
setMovieList(matches);
}, [search, movies])
return (
<Container maxWidth={false} disableGutters>
<Search setSearch={setSearch} />
<Lists movies={movieList} />
</Container>
);
};
export default Movies;