Importing local json data using lazy load in next js

229 Views Asked by At

I have a locally stored json in my project, which is an array containing around 200+ items.

Example: data.js

const data = [
  {
    title: 1
  },
  {
    title: 2 
  },
  ...
  {
    title: 200
  }
];

My Component:

import {data} from "../mocks/data.js";

I am thinking of a way to use the json data for sometime until I have a database setup, but importing 200+ records slows up the page.

Is there a way I can lazy load the locally json data?

1

There are 1 best solutions below

1
chagatai On

First of all, your example is a JavaScript object, not a JSON.

Secondly, The use hook may help you in this problem.

import { use } from 'react';

const data = use(import('./data.json'))

Also, there is a 3rd-party module to read in JSON data called json-loader, which is already included in create-react-app.

import customData from '../customData.json';

IMHO, I don't think that importing 200+ records in JSON slows up the page dramatically, but nevertheless these solutions may help you once you convert your mock data to a JSON.