Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

291
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda