How to pass an array and the array set by the value of the Provider (CONTEXT - TYPESCRIPT - REACT)

Asked

Viewed 127 times

0

How to pass the value of the list and sector?

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>
  )
}
  • I don’t understand your question

  • I got the answer in the English stackoverflow. Follow with the answer: https://stackoverflow.com/questions/62304400/how-pass-a-array-and-setarray-in-value-of-provider-react-typescript-context

1 answer

1


I obtained a solution through the English stackoverflow. was as follows:

import React from "react";

interface List {
  name: string;
  setor: string;
  ramal: number;
}

interface ListContextValue {
  list: List[];
  setList: (data: List[]) => void;
}

interface Props {
  children: React.ReactNode;
}

const listInitial: ListContextValue = {
  list: [
    {
      name: "",
      setor: "",
      ramal: 0
    }
  ],
  setList: data => {}
};

const ListContext = React.createContext<ListContextValue>(listInitial);

export default function ListProvider({ children }: Props) {
  const [list, setList] = React.useState<List[]>([]);

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

  return (
    <ListContext.Provider value={{ list, setList }}>
      {children}
    </ListContext.Provider>
  );
}

export function useList() {
  const context = React.useContext(ListContext);
  const { list, setList } = context;
  return { list, setList };
}

Source: https://stackoverflow.com/questions/62304400/how-pass-a-array-and-setarray-in-value-of-provider-react-typescript-context

Browser other questions tagged

You are not signed in. Login or sign up in order to post.