I have a problem with the getItem of my localStorage in my React Form. I put a onChange attribute:
<div className = 'InputForm' onChange={save_data}>
I found the setItem function to store the data in. Here is the function:
function save_data(){
let textarea = document.querySelectorAll("textarea")
let input = document.querySelectorAll("input[type='text']")
let saved_fields = []
textarea.forEach(x => {
saved_fields.push({
key: x.className,
value: x.value
})
})
input.forEach(x => {
saved_fields.push({
key: x.className,
value: x.value
})
})
localStorage.setItem("saved_data", JSON.stringify(saved_fields))
}
My main problem is that I don't find a way to put the data back to the page after the page reload. I just found out how to persist all my inputs in the console:
window.onload = dataLoad();
function dataLoad () {
let show_saved_data = localStorage.getItem("saved_data");
console.log('show_saved_data:',JSON.parse(show_saved_data));
}
Can you guys help me find the retrieve/persist data function?
Edit : Here is the html of the form, i use props from another component. I don't know if this can change the function i need to use.
<InputFields
stateKey = 'contactInfo'
key = {props.contactInfo.id}
completedFields = {props.contactInfo}
templateFields = {props.templates.contactInfo}
onDataEntry = {props.onDataEntry}
newField = {props.newField}
/>
Can we have your HTML form to help you? You should not identify your inputs / textareas by their className.
After that, by using ID as identifiers for your input / textarea, you just have to do it in reverse:
Get your input/textarea list
forEach items, set the value based on the ID
function dataLoad () {
var show_saved_data = localStorage.getItem("saved_data");
var inputList = JSON.parse(show_saved_data);
inputList.forEach(x => {
document.getElementById(x.key).setAttribute('value', x.value);
})
}
Giving us your complete HTML/JS will be easier to give you a complete solution.
Related
In a table, certain input text fields are displayed. Accordingly data could be inputted in it. My intention is to club all the input data into an array. Each record has its specific unique id, which we get in console while we input in text box. Based on this id, I want to club into an array data. I've tried with one logic but gives error. Please have a look at the code below
// Here newData is an array of records which I'm displaying in Grid
const [dataNew, setDataNew] = useState(newData);
const textChange = (data) => {
const { id, value } = data;
setDataNew((prevInfo) => {
const dataIndex = +id[id.length - 1];
return {
...prevInfo,
// Here I'm getting error in the below code snippet in prevInfo
dataHere: Object.assign([...prevInfo.newData], { [dataIndex]: value })
};
});
};
console.log('NEW DATA', newData)
Please suggest me if any changes to be done. Any solution highly appreciated
Please refer codesandbox link --> https://codesandbox.io/s/elated-varahamihira-xpjtdb?file=/src/Table.js:149-197
dataNew is initially an array, but you are returning an object from the setDataNew callback.
Also id is a number itself in your sandbox, so the following would suffice:
const textChange = (data) => {
const { id, value } = data;
setDataNew((prevInfo) => {
const dataIndex = id - 1;
prevInfo[dataIndex] = value;
return [...prevInfo];
});
};
In a React project, I'm displaying certain records in a table which also has input text boxes for changing the values when needed. To process those changed records it needs to be added into an array, but, getting undefined when changed the values. Although each record is associated with unique id, unable to add in new array. Please refer to the code below.
const textChange = (data) => {
const { id, value } = data;
setDataNew((prevInfo) => {
// Here the records are getting undefined and not getting added into array
const dataIndex = id - 1;
prevInfo[dataIndex] = value;
return [...prevInfo];
});
};
Any suggestions and solution highly appreciated.
Please refer to code sandbox link for better clarity --> https://codesandbox.io/s/elated-varahamihira-xpjtdb?file=/src/Table.js:757-959
If I understood it correctly here is what you need to do if you need all the records which got updated :
const textChange = (data) => {
const { id, value } = data;
setDataNew((prevInfo) => {
const newList = [...prevInfo];
const index = newList.findIndex((datum) => datum.id === id);
if (index !== -1) {
newList[index] = { id, value };
} else {
newList.push({ id, value });
}
return [...newList];
});
};
Mistake in your code
You were getting undefined because you were calculating index like :
const dataIndex = id - 1;
if the changed object id was 6708 , you were adding element at 6707th index. Hence all first 6706 element were showing up as undefined.
Link : working demo
everyone, I have some problem with fetching data and displaying message on initial loading as well as when I change some of the input filed value. The idea here is to display specific message in two cases after doing some calculation.
const potrosnja = document.getElementById('potrosnja');
const nagib = document.getElementById('nagib');
const input = document.querySelectorAll('input[type="number"]');
const submitBtn = document.getElementById('submitBtn');
const poruka = document.getElementById('poruka');
let str = document.querySelector('input[name="strane-sveta"]:checked').value;
let godisnjaPotrosnja = parseInt(potrosnja.value);
let nagibKrovaInput = nagib.value;
//On button submit it fetches data and calculate the value needed for yearly consumption of energy
//fetching data
async function dataFetch(){
let response = await fetch('./csvjson.json')
let data = await response.json();
data.map(strana => {
strana.strana.map((item, i) => {
try {
if(item == str && nagibKrovaInput == strana.nagib) {
let result = Math.ceil(godisnjaPotrosnja / strana.vrednost[i]);
console.log("try works")
poruka.innerHTML = `You need <span class="kw">${result}</span>`
}
}
catch(err) {
poruka.innerHTML = `Please fill required fields.`
console.log(err)
}
})
})
}
//event listeners
submitBtn.addEventListener('click', () => {
dataFetch()
console.log('clicked')
input.forEach(input => {
if(input.value == ''){
input.classList.add("active");
}
})
})
I can see that the problem is inside try function, it like condition isn't treated on initial load, and I have to reload page so it would work. Can someone help me understanding what is the problem?
Ok, I found solution... First thing I have to do Is to check if nagibKrovaInput == strana.nagib, after I get true, I compared does the indexOf item is equal as str and after I get true, it will display something. I also changed on click on the button to send values to data function as an arguments and It solved the problem. Tnx for help.
I am not able to discover the problem that is causing the function to be executed more than once.
The code snippet below is when the page is opened or when there has been a change, whether new or changed data. This function takes the data from the bank and shows, this part I will not show because it is unnecessary. After showing it, it calls two functions and it is the first one that is giving me a problem, the update function.
function carteProduct_listProducts() {
let dataProductsDatas = document.getElementById("data_products_datas");
firebase.database().ref("Products").on("value", snapshot => {
dataProductsDatas.innerHTML = ""
snapshot.forEach(element => {
...
});
// Edit buttons event listener
// Update
modalEditProduct()
// Delete
realtimedb_delete("Products");
})
}
Then comes the update function, or as it is in the code, modalEditProduct.
I made a modal just for that, because I was having trouble using only one modal.
So, this function is called there in the other function. And I thought it was because of this that I was giving this problem, the function being executed twice, but no! I took the function out of there and tested it, but the problem keeps happening.
Then, when an edit button is clicked, the modal opens. So it performs some functions that are within that same function
// Update product
function modalEditProduct() {
let editBtns = document.querySelectorAll("#data_products_datas .editBtn");
let productTitleInput = document.querySelector("#modalEditProduct form input[name='productTitle']");
let productCategoryInput = document.querySelector("#modalEditProduct form select[name='productCategory']");
let productPriceInput = document.querySelector("#modalEditProduct form input[name='productPrice']");
let productIngredientsInput = document.querySelector("#modalEditProduct form input[name='productIngredients']");
let productDescriptionInput = document.querySelector("#modalEditProduct form input[name='productDescription']");
let editSubmitBtn = document.querySelector("#modalEditProduct form button");
console.log(editBtns)
editBtns.forEach(element => {
element.addEventListener("click", (e) => {
let key = e.target.id;
// Open modal
modal_openModal("modalEditProduct");
// Get the data
let data = getData(key);
// putting categories on select
cartePorudct_puttingCategoriesSelect(productCategoryInput);
// let children = productCategoryInput.children;
// console.log(children)
// for (let i = 0; i < children.length; i++) {
// const element = children[i];
// console.log(element)
// }
// Insert the data in the field/inputs
setData(data);
// Submit form
editSubmitBtn.addEventListener("click", (e) => {
e.preventDefault();
realtimedb_verification("modalEditProduct", edit_productData, key)
})
})
});
// Get the data
function getData(key) {
let data;
firebase.database().ref("Products/"+key).on("value", snapshot => {
data = {
title: snapshot.val().title,
category: snapshot.val().category,
price: snapshot.val().price,
ingredients: snapshot.val().ingredients,
description: snapshot.val().description,
}
});
return data;
}
// Insert the data in the field/inputs
function setData(data) {
productTitleInput.value = data.title;
// productCategoryInput.value = data.category,
productPriceInput.value = data.price;
productIngredientsInput.value = data.ingredients;
productDescriptionInput.value = data.description;
}
// Submit form
function submitForm(btn, key){
}
// Data
function edit_productData(key) {
let data = {
title: productTitleInput.value,
category: productCategoryInput.value,
price: productPriceInput.value,
ingredients: productIngredientsInput.value,
description: productDescriptionInput.value,
}
// Update
realtimedb_update("Products", key, data);
}
}
Anyway, the problem is. When I open a modal, make a change and save, everything is fine. If I open the modal of another data, the previous data will also be changed with the value of that data after I click the submit button. And if I open a third modal, everything happens again.
Every time you call modalEditProduct(), you add a new event listener to each of those editBtns.
That means that the first time you've called modalEditProduct() and click a button, it does its thing once. After a second call, the buttons now have two click event listeners, so clicking them will do a thing twice, etc.
Hoping someone out there could tell me where I am going wrong with this update method:
changeTaskDetails: function(singleID,detailsTarget){
TaskDetails.update({
_id: singleID,
}, {
$set:{
projectType: detailsTarget,
}
});
console.log(singleID);
},
Here is the event:
'submit #editTaskDetails'(event){
event.preventDefault();
var id = FlowRouter.getParam('taskId');
const singleDetailsUpdate = Tasks.findOne({_id:id});
const singleID = singleDetailsUpdate._id;
const target = event.target;
const facilityTarget = target.facilityName.value;
const inspectorTargetName = target.detailsinspector.value;
const inspectorIdTarget = target.inspectorid.value;
const detailsTarget = target.detailstype.value;
const dateTarget = target.TaskDate.value;
console.log(singleID)
Meteor.call("changeTaskDetails", singleID,detailsTarget);
},
I can get the 2 props to log...but its not updating the DB. No errors in either console.
I figured it out! I had a session variable controlling when you could (or could not) see the update form. For one reason or another the form crapped out when inside of this area. When I removed the session, and added the form to the main template...it worked!