Tips for using useState with dependencies on custom objects such as { filter[], sort[] }:

I am trying to use the useState Hook with a custom object that contains two arrays as shown below

const [initConfig, setInitConfig] = useState<>({filter:[], sort:[]});

However, I am unsure of how to declare inside the angle brackets.

The filter array will consist of items of type:

export interface IFilterTerm {
    key: string;
    criteria?: CriteriaType;
    value: string;
}

The sort array will have items of type:

type ISortGridItem = {
    colId: string | undefined;
    sort: string | null | undefined;
}

I am setting values like this:

setInitConfig({
      filter : [...persistentConfig.filter],
      sort : [...persistentConfig.sort]
    });
const persistentConfig = {
    filter: [ 
      { key:TIME, criteria: CriteriaType.DataRange, "value":"currentBusinessDay"},
      { key:INCLUDE_SYNTHETIC_LEGS, criteria: CriteriaType.Equals, value:"false" },
      { key:"waterfall", criteria: CriteriaType.Equals, value:"true" } 
    ],
    sort: [
      {
        colId: "time",
        sort: "asc"
      }
    ]
  }  

I attempted to declare useState like this:

const [initConfig, setInitConfig] = useState<{ filter: IFilterTerm[] , sort: ISortingTerm }[]>({filter:[], sort:[]});

Unfortunately, it did not work and I received an error message:

Argument of type '{ filter: never[]; sort: never[]; }' is not assignable to parameter of type '{ filter: IFilterTerm[]; sort: ISortingTerm; }[] | (() => { filter: IFilterTerm[]; sort: ISortingTerm; }[])'
Types of property 'filter' are incompatible.
Type 'never[]' is not assignable...

Answer №1

Your TypeScript code contains a typo:

const [initConfig, setInitConfig] = useState<{ filter: IFilterTerm[] , sort: ISortingTerm }[]>({filter:[], sort:[]});

In the line where you have

useState<{ filter: IFilterTerm[] , sort: ISortingTerm }[]>
, the array brackets are incorrectly placed. They should be next to ISortingTerm, not surrounding the entire object. The correct syntax is:

const [initConfig, setInitConfig] = useState<{ filter: IFilterTerm[] , sort: ISortingTerm[] }>({filter:[], sort:[]});

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

Retrieving the output value from a callback function in Sqlite3

In my current project, I am using Sqlite3 with an Express backend along with a React frontend. My goal is to verify if a user with a specific email exists in the database. While working on the function provided below, which is still a work in progress, I e ...

The error page is requesting a root-layout, which indicates that having multiple root layouts is not feasible

My issue is as follows: The not-found page located in my app directory requires a root-layout which I have added to the same directory. However, this setup prevents me from using multiple root layouts in the structure below. How can I resolve this? It see ...

Click the edit button to access the options in the material table

https://i.stack.imgur.com/Inyow.png Currently, I am utilizing Material Table within Reactjs to display the table Data. However, I have encountered a hurdle where I need to alter state upon clicking on the edit option/icon. My objective is not to modify th ...

There seems to be a glitch in my programming that is preventing it

Can someone please help me troubleshoot this code? I'm unable to figure out what's going wrong. The concept is to take user input, assign it to a variable, and then display a string. However, nothing appears on the screen after entering a name. ...

Is it possible to keep adding the keys of an array to themselves until reaching a specified limit

Given an array var ary = [5,10,28,50,56,280], I am exploring the idea of generating all possible combinations or subsets of this array until a certain threshold is reached. The objective is to store this limit in a variable and collect all the elements be ...

Addressing Memory Leakage Issues in a Basic Node.js Application

Out of sheer curiosity and as an experiment with NodeJS, I decided to write a basic program to test the Collatz Conjecture for an incredibly high number of integers. While this concept should work fine in theory, my simple code is unexpectedly facing a mem ...

Updating an array with complex values in React using the useState hook in

I am working with a long array where I need to update the quantity under the misc array for each person. Each person in the array has a list of miscellaneous items, and each of those items can have their own array with quantities that need to be updated. T ...

Having trouble with installing "npm install semantic-ui-react semantic-ui-css"? Any ideas on how to fix it?

Encountered an error while trying to install Semantic UI React and Semantic UI CSS: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [ema ...

When handling cross-domain Jquery Ajax requests, the error function may unexpectedly return a success status

While attempting a cross domain GET request using jQuery AJAX, I am encountering a situation where the error function returns success as the status. The data I am expecting to be returned from the get service is: document.write("<div class=\"displ ...

Rendering a ImageBitMap/Image on an OffScreenCanvas using a web-worker

In my vue.js application, I have implemented vue-workers/web-workers to handle image processing tasks such as scaling and cropping in the background after a user uploads images. Due to the lack of support for Canvas and Image Object in web workers, I opte ...

Utilizing TypeScript for various return types with the same parameters

Exploring TypeScript Signatures In an effort to embrace TypeScript fully, I am implementing strongly typed signatures in my Components and Services, including custom validation functions for angular2 forms. I have discovered that while function overloadi ...

Illuminate objects using three.js

My expertise in shaders and three.js is limited, however I am currently experimenting with creating a dynamic glowing effect similar to lights being flicked on and off. Currently, I am adjusting the color saturation and lightness which somewhat achieves ...

What is preventing the selected values of a dropdown element from being set?

Although it may seem simple to assign values to select elements, I'm puzzled as to why the code below is setting the values to null instead of the correct ones for "form-type" and "genre". All other fields are being set correctly. It's worth not ...

Error: Unable to execute _this2.setState in react - potential problem with binding

I am completely new to utilizing react, and I have been encountering difficulties in pinpointing the root cause of this error that keeps popping up in the chrome console bundle.js:15316 Uncaught (in promise) TypeError: _this2.setState is not a function M ...

"Utilizing JSON.parse() to convert a string captured from a PythonShell back

Using PythonShell in Node to execute a Python script that generates a Python dict, such as: { "playedStatus": game['playedStatus'].encode('ascii'), "awayTeamAbb": game['awayTeamAbb'].encode('ascii'), "homeTeamAbb": ...

Using the JS confirm function to switch the Vuetify checkbox in a Vue 2 application

It's been a real struggle trying to figure out this issue. I have a v-dialog that contains a checkbox. When the checkbox is clicked, a confirm() method is triggered to open a dialog in the browser to confirm the selection. After confirming, the check ...

The output of server.address() method in Node.js is ::

My memory serves me right, a few days back it was showing "localhost". I'm puzzled as to what altered server.address().address to now return double colons (::). According to my research, it seems to be returning an IPv6 address (::) because it's ...

.forEach returns an undefined value for each length

Having trouble with my if statement. It seems like the else block is working fine, but the if section is not functioning as expected. The variable count1 comes out as undefined. Interestingly, the conditions inside the if statement are working correctly ...

Is it necessary for the Jquery Component to return false?

I'm currently working on developing a jQuery module using BDD (Behavior-driven development). Below is the code snippet for my component: (function($) { function MyModule(element){ return false; } $.fn.myModule = function ...

Implementing a jQuery method in a PHP page that is loaded through AJAX

I am facing an issue on my page where I am using jquery/ajax to load a series of buttons into a div. This script loads buttons every time the user scrolls the page and each button should run a jquery function when clicked. The problem arises when I switche ...