skip to Main Content

Is it not possible to store data to JSON file ? I mean I want to store the questions from the UI. I haven’t started my database concepts yet. I know it is far far efficient to use Database.

Can anyone tell me if it is not at all possible.

Thank you

I just now studied how to get data and it worked. But when i tried to search for storing data I wasn’t getting any results

2

Answers


  1. In a React.js application, you can store data in a JSON file. You can read the JSON file using the fetch API or any other method, parse its contents, and then use the data within your React components.

    Here’s an example of how you can read data from a JSON file in a React component:

    import React, { useState, useEffect } from 'react';
    
    const MyComponent = () => {
      const [questions, setQuestions] = useState([]);
    
      useEffect(() => {
        const fetchData = async () => {
          try {
            const response = await fetch('questions.json');
            const data = await response.json();
            setQuestions(data);
          } catch (error) {
            console.error('Error fetching data:', error);
          }
        };
    
        fetchData();
      }, []);
    
      return (
        <div>
          <h1>Questions</h1>
          <ul>
            {questions.map(question => (
              <li key={question.id}>{question.question}</li>
            ))}
          </ul>
        </div>
      );
    };
    
    export default MyComponent;
    

    Also I recommend using json-server (https://www.npmjs.com/package/json-server )

    Check it out

    Login or Signup to reply.
  2. You can make a data.json with data for each api and run that json file in a server using command called npm run json:server

    Add in package.json under scripts
    "json:server":"json-server –watch –port "

    Then run npm run json:server server will run

    After that you can call the data such as calling to API sample API will be http://localhost/getNames

    You can add more data and run again too

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search