简体   繁体   中英

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;

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)!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM