Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

290
Visualizações
Reading JSON file into React Context Provider with Typescript

My React Typescript app has a Context Provider DataProvider that is to read a value from a JSON file and provide it in the Context useData(). I am trying to do the read synchronously to avoid having to deal with a isLoading since this is a tiny local JSON file.

Is there a recommended way to read the JSON file synchronously inside a Context Provider?

I tried the following using node-sync, but its giving a Typescript error

Object is possibly 'undefined'.ts(2532)

on data at line

return data.find(...

Tried changing it to

return data?.find(...`

but now the error is

Property 'find' does not exist on type 'never'.ts(2339)

import React, {
    createContext,
    useContext,
    Consumer,
    Context,
    ReactNode,
    useMemo,
  } from 'react';
  
import Sync from 'sync';

export interface DataProviderProps {
    children: ReactNode;
}
  
export interface Data {
    secretNumber?: string;
}

// @ts-ignore
const DataContext: Context<Data> = createContext<Data>();

export function DataProvider({ children }: DataProviderProps) {
    const secretNumber = useMemo(() => {

      // Read from JSON file
      const contractFile =
        process.env.REACT_APP_WORLD === 'main'
          ? '../main.json'
          : '../test.json';
      let data;
      Sync(function () {
        data = import(contractFile);
      });
  
      return data.find( // <=== TS error: Object is possibly 'undefined'.  ts(2532)
        ({ name }: { name: string }) => name === 'elonmusk',
      )?.secretNumber;
    }, []);
  
    const states = useMemo<Data>(() => {
      return {
        secretNumber,
      };
    }, [secretNumber]);
  
    return (
      <DataContext.Provider value={states}>
        {children}
      </DataContext.Provider>
    );
  }

export function useData(): Data {
    return useContext(DataContext);
}
  
export const DataConsumer: Consumer<Data> = DataContext.Consumer;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

array.find() returns undefined If no values satisfy the testing function, from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find, so just add (!) after the array.find()! fxn to ascertain a value would be returned.

sample code stub
data.find(todoCodeStubhere)!
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda