`Filter an array retrieved from the backend in a TypeScript environment`

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;

Answer №1

Upon examining the code, two key issues have come to light:

  1. The state definition is incorrect due to an erroneous generic type
  2. The useAppSelector function is returning a never type

To address the first problem, it is recommended to accurately define the movieList state with the appropriate type as shown below:

const [movieList, setMovieList] = useState<movie[]>(movies); 

Regarding the second issue, ensure that the redux-toolkit types are correctly set up by referring to the documentation available at: https://redux-toolkit.js.org/tutorials/typescript#define-root-state-and-dispatch-types

If all previous attempts prove unsuccessful, consider casting the return type of the hook to a custom type similar to this example:


type MovieReducer = {
  movies: movies[];
  message: string; // Verify if this matches the required type
}

const { movies, message } = useAppSelector((state) => state.movies) as unknown as MovieReducer;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Do I need to utilize getStaticProps along with JSON imports in Next.js?

Is it necessary to use getStaticProps in order to render static data from a JSON or typescript file, or can the data be imported without using getStaticProps? The documentation I read didn't provide a clear answer. projects.tsx const projects: [ { ...

Guide to implementing a Page Object Model for improved debugging of Protractor tests

Introduction I am on a mission to streamline my e2e testing code using the Page Object Model for easier maintenance and debugging. My Approach When embarking on creating end-to-end tests with Protractor, I follow these steps to implement the Page Object ...

Navigating through JSON array in Python

I'm currently working with JSON data stored in an array that I am importing into my script. "ip_address": [ "192.168.0.1", "192.168.0.2", "192.168.0.3" ] Upon loading the JSON, I define a variable called ip_address. data = yaml.load(message) fo ...

Implementing typing for a module that exports an instance of a particular class

Attempting to create a .d.ts file for the foo-foo-mq module has presented some challenges. Following the documentation, a 'foo-foo-mq' folder was created within the 'typings' directory at the project's root. An index.d.ts file was ...

Why does the pound symbol in z-index always show up in Angular?

Having an issue with my code where I set a z-index in the CSS like this: .mat-mini-fab { position: absolute; right: 5px; top: 4px; z-index: 999; box-shadow: none !important; } However, whenever I visit my site, the z-index is not being appl ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

Extracting multiple values from a JSON object with an array as the root in Swift 5

As a newcomer in the world of app development, I am embarking on my first iOS project which involves creating a currency table/converter for Ukrainian Hryvna. To populate a TableView with data, I plan to retrieve information from a JSON file accessed throu ...

Designing unique page transitions with Next.js

Currently, I am attempting to achieve callback-based route transitions utilizing the Next.js framework and Greensock animation library. For instance, when moving from the homepage to /about, my goal is to have something like: HomepageComponent.transitionO ...

Using Angular's ng-repeat to iterate through an array and display its objects within another array

One of my tasks involves retrieving json objects through a simple post method. The json contains multiple campaigns, organized in an array structure. Each campaign holds slots, which are also arrays with one or more base_image elements. My goal is to di ...

Tips for obtaining a shipping address during a Stripe subscription Checkout process

I have been developing an innovative online subscription service designed to deliver products directly to customers' homes. Despite being able to collect their name, zip code, and payment details, I have encountered a peculiar issue where they are not ...

Implementing Global Value Assignment Post Angular Service Subscription

Is there a way to globally assign a value outside of a method within my app component? This is how my service is structured: import { NumberInput } from '@angular/cdk/coercion'; import { HttpClient } from '@angular/common/http'; import ...

Angular obtains an undefined response from a service

Having trouble retrieving the data from my service. Working with Angular 8. Here's the code snippet: Within the service: query(url: string) { this.subscription = this.socket$.subscribe( (message) => { return message; }, ...

The React date picker has limitations, as there are certain dates that users are unable

Recently, I came across an issue with a react date picker that I am using. Here is the code snippet: <DatePicker selected={selectedDate} onChange={handleDateChange} minDate={new Date()} className="form-control" /> In this image, when ...

Typescript-powered React component for controlling flow in applications

Utilizing a Control flow component in React allows for rendering based on conditions: The component will display its children if the condition evaluates to true, If the condition is false, it will render null or a specified fallback element. Description ...

create an endless loop to animate in angular2

Is there a way to add iterations, or something similar to the ccs3 animation-iteration-count in Angular 2 animations? I've looked but can't find anything related. How can we apply an infinite play to the animation? Where should we include that o ...

The use of cURL to send a POST array is resulting in an error message stating "Invalid

I am attempting to send an array of data from one domain to another using cURL. When I run the code below, I encounter the error message "Invalid argument supplied for foreach()". I have a suspicion that the issue lies with the array after it has been deco ...

Image missing aria-label attribute

I am facing an issue with getting the aria-label to display on my image. Despite checking my code, I cannot figure out why it is not working. Any ideas on what might be missing? Here is the code from my NextJS app: The svg in my public folder. <?xml v ...

Angular 2 Date Input failing to bind to date input value

Having an issue with setting up a form as the Date input in my HTML is not binding to the object's date value, even though I am using [(ngModel)] Here is the HTML code snippet: <input type='date' #myDate [(ngModel)]='demoUser.date& ...

There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance? Here is my folder structure: src --assets ---a ...

Introducing the initial landing page made with react and next.js framework!

Could you provide me with some examples of a page that only renders once? I am curious to see how this feature is implemented by others. I have been using next.js and attempted to save data not in local storage but using cookies instead. While it works, I ...