Home > Software design >  Updating property values of JSON object arrays (React JS)
Updating property values of JSON object arrays (React JS)

Time:09-27

I'm trying to map all the "failed subjects and their points" into one array and add a button for each subject that will increase value of points but only for the item clicked.

JSON file:

{
    "firstyear": {
        "passed": [{ "name": "English", "points": 0 }, { "name": "History", "points": 0 }],
        "failed": [{ "name": "Chemistry", "points": 0 }, { "name": "Agrictulture", "points": 0 }]
    },
    "secondyear": {
        "passed": [{ "name": "Medicine", "points": 0 }, { "name": "Arts", "points": 0 }],
        "failed": [{ "name": "Gym", "points": 0 }, { "name": "German", "points": 0 }]
    },
    "thirdyear": {
        "passed": [{ "name": "Math", "points": 0 }, { "name": "Informatics", "points": 0 }],
        "failed": [{ "name": "French", "points": 0 }, { "name": "Economics", "points": 0 }]
    },
    "fourthyear": {
        "passed": [{ "name": "Litretarue", "points": 0 }, { "name": "Philosophy", "points": 0 }],
        "failed": [{ "name": "Politics", "points": 0 }, { "name": "Gardening", "points": 0 }]
    }
}

Subjects.js:

import {fetchAll} from '../AppFetch';
import {useEffect, useState} from 'react';

export default function Subjects() {

    const [data, setData] = useState({});
      
    useEffect(( ) => {
      fetchAll("http://localhost:3000/example.json", setData)
    }, []);

    const failedArr = [];

    for(let i=0; i<Object.entries(data).length; i  ){
      const status = Object.values(data)[i];
  
      for(let j=0; j < Object.keys(status).length; j  ){
        const failed=Object.entries(status)[j][1]
        
        failedArr.push(failed[j])
      }
    }
    
    return <div className="row">
      {failedArr.map(key => (
        <div key={key.name}>
          <button>Add point</button>
          <p>{key.name} - {key.points}</p>
        </div>
      ))}
    </div>;
} 

After increasing the values they should be updated in the local JSON file.

Whatever I try isn't working so please help if you can.

CodePudding user response:

This task can not be done from frontend. You need a backend server for handling any "write-to-file" task. You can use Node.js express or another alternative.

  • Related