I have a data.json file in my local workspace environment. The app is client side only.

I'm uncertain if the best (advised) way to consume such data is either via:

import data from './data.json'
// and got to town on it...

Or if I should bring that data into my React Component via a GET request (fetch, axios, etc) where I'd place it inside of a componentDidMount


async componentDidMount() {
    const data = 'http://localhost:3000/data.json'
    try {
      const res = await fetch(data)
      this.setState({res})

    }
    catch (error) {
      console.error(error)
    }
  }

  • What's the correct approach and best practice to go about this?
  • Should CRUD requests only be used for external https end-points and not for local data like my example?
  • Feel free to suggest a third approach if I missing anything here.

3 Answers

2
jsdeveloper On Best Solutions

I would suggest using the first method (import data from...) for the following reasons:

  1. Less to go wrong. Less code, fewer bugs.
  2. Eliminates CORS and other network issues.
  3. No hardcoded urls. These will break as soon as you're not using localhost anymore ie a deployed environment.
1
Dennis Vash On

The third option is to declare your object inline:

import React, { useState } from 'react';

const algorithmTemplate = {
  "name": "",
  "description": "",
  "nodes": [
    {
      "nodeName": "",
      "algorithmName": "",
      "input": []
    }
  ]
}

export default function AddAlgorithm() {
  const [formData, setFormData] = useState(algorithmTemplate);

  return (...)
}

Vs. using import

import React, { useState } from 'react';
import algorithmTemplate from 'config/algorithm.template.json';

export default function AddAlgorithm() {
  const [formData, setFormData] = useState(algorithmTemplate);

  return (...)
}

I would choose readability, it depends on your JSON size, etc.

1
Community On

I think the first way is better.

  1. The second one is an asynchronous process. Here you only see the word 'async' but if you convert that 'async' thing into es5 javaScript, you will see how much-hidden code is there. More code, More process, More memory usage, less speed. So the first way is better.
  2. What you gonna do after deploying your application to the real world? Are you gonna change all the places where you wrote localhost:3000?
  3. The meaning of the word 'fetch' is 'go for and then bring back'. Your application doesn't even have server-side logic. So where you go from your front end? just from one directory to another?

  4. If your JSON file is too large, then you have to use server-side logic to handle your database. At this point, you have to use a fetching thing.