0

I am very new in React Native. I have been trying to edit a data to an existing array Data file. lets make it more clear. I have a datafile name testData.js. where the data looks like this

const TestRoomData=[
    {
        id:"001",
        date:"24-April-2020",
        diagnosis: "seasonal flue",
        result:"this is some details on the result",
        prescription:"tamiflu",
        key: "33325254",
    },
    {   
        id:"002",
        date:"22-April-2020",
        result:"this is some details on the result editable",
        diagnosis: "Arthritis",
        prescription:"tamiflu",
        key: "33325255",
    }
];
module.exports= TestRoomData;

So I am showing the data through a flatlist by simply importing the data. Is there any way I can make some change to this list of data through textInput? In my flatList it has a button which navigate to Edit Screen. and in Edit Screen there are few text input.I understand how to pass the data between screens and I am able to pass it as placeholder. All I want is to make change in TestRoomData .

Could you please elaborate the process of just editing the data in my scenario please?

I have a long way to go learning, a little help is much much appreciated. Thank You

Zeed Tanue
  • 91
  • 1
  • 15

1 Answers1

1

You can modify the test data array at runtime, but you will not be able to persist those changes if you don't save them somewhere.

Just do:


// Change it to "let" as it is not a constant variable.
let objTestData = [
    {
        abc: 1,
        def: 2
    },
    {
        abc: 2,
        def: 3
    }
];


function addToTestData(obj) {
    objTestData.push(obj)
}

module.exports = {
    objTestData,
    addToTestData
}

Then, import the "addToTestData" method

import React, { Component } from 'react';
import { addToTestData } from './testData.js'

class MyComponent extends Component {
     //...

     myMethod = (obj) => addToTestData(obj)

     //...
}

You can't directly modify the test data array because, in ES6, imports are read-only live views of the exported values. Instead, you should modify the array by using an imported method that has access to it.

NOTE Please, take in to account that those changes will not persist after an application restart. If you want the data to persist, you should use some data storage solution as AsyncStorage

Angel González
  • 108
  • 1
  • 4