typescriptnext.jsnext.js13supabase

How to solve Argument of type 'any[] | null' is not assignable to parameter of type 'SetStateAction<never[]>'. in nextjs 13


my project was created by Nextjs 13 based on Supabase database, am trying to fetch some data from supabase and use usestate to assign it to an variable ,, but am getting this error :

Argument of type 'any[] | null' is not assignable to parameter of type 'SetStateAction<never[]>'.
  Type 'null' is not assignable to type 'SetStateAction<never[]>'.

Here is a part of the code am using :

import { createClient } from '@supabase/supabase-js';
import { useState } from 'react';

export default function SubCategoryTable() {
  const [subCategories, setSubCategories] = useState([])
  async function fetchSubCategories() {
    const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL as string
    const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY as string

    const supabase = createClient(supabaseUrl, supabaseAnonKey);
    const { data: subCategories } = await supabase.from("sub_categories").select();
    setSubCategories(subCategories)
  }
  fetchSubCategories();

  return (
.....

the error is found in this line setSubCategories(subCategories)


Solution

  • useState identifies the type of the state either by the manually passed generic type or by the initial value itself. In your case, there is no generic parameter and the initial value is an empty array, which is never[] for the compiler. To fix the problem you should set the correct type to the state. In your case, it seems to be any[] | null.

    const [subCategories, setSubCategories] = useState<any[] | null>([])
    

    This should do the job