How pass a array and setArray in value of provider (React, Typescript, Context)

Viewed 3132

How can I pass an array and setArray in value of provider? My main problem is how to create an interface for this, because it says incorrect type.

The Array contains objects List and I need consult this Array and set to use a filter later.

import React from "react";

interface Lista {
  nome: string,
  empresa: string,
  ramal: number
}

const listaInicial: Lista = {
  nome: "",
  empresa: "",
  ramal: 0
}

interface Props {
  children: React.ReactNode
}

const ListaContext = React.createContext<Lista>(listaInicial);

export default function ListaProvider({children}: Props) {
  const [lista, setLista] = React.useState<Lista[]>([]);

  React.useEffect(() => {
    setLista([
      {
        nome: "nome 1",
        empresa: "matriz",
        ramal: 2000
      },
      {
        nome: "nome 2",
        empresa: "matriz",
        ramal: 2001
      },
      {
        nome: "nome 3",
        empresa: "sede",
        ramal: 2002
      },
      {
        nome: "nome 4",
        empresa: "sede",
        ramal: 2002
      },
    ])
  }, []);

  return (
    <ListaContext.Provider value={{lista, setLista}}>
      {children}
    </ListaContext.Provider>
  )
}
2 Answers

You need to create a different interface for React.createContext

For example:

    interface ListaContextValue {
     lista:Lista[],
     setLista:(data:Lista[]) => void
    }

    const listaInicial: ListaContextValue = {
      lista:[
       {nome: "",
        empresa: "",
        ramal: 0
       }],
      setLista: (data) => {}
    }

And then,

const ListaContext = React.createContext<ListaContextValue>(listaInicial);

React.createContext<Lista>(listaInicial); mean the return value of ListaContext.Provideris Lista type. If you want to set value of provide is lista and setLista you can try this to not defined the type for createContext.

const ListaContext = React.createContext(listaInicial);

Or

const ListaContext = React.createContext<{lista: Lista[], setLista:React.Dispatch<React.SetStateAction<Lista[]>> }>(listaInicial);
Related