I have an array of objects called audioBaby.
When the app launches I check asyncStorage and if any key has value active, I want to update the lock keys in the array.
What I have done is not updating all objects in array but only the last object.
How can I initially update the array from asyncStorage and render the screen?
const [audioBaby, setAudioBaby] = useState([
{
lock: "deactive",
url: "item0.mp3",
},
{
lock: "deactive",
url: "item1.mp3",
},
{
lock: "deactive",
url: "item2.mp3",
},
]);
useEffect(() => {
try {
AsyncStorage.multiGet([
"babyAudio0Status", //value: active
"babyAudio1Status", //value: active
"babyAudio2Status", //value: active
]).then((response) => {
let updatedList = audioBaby;
if (response[0][1] != "null" && response[0][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item0.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
if (response[1][1] != "null" && response[1][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item1.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
if (response[2][1] != "null" && response[2][1] == "active") {
updatedList = audioBaby.map((item) => {
if (item.url == "item2.mp3") {
return { ...item, lock: "active" };
}
return item;
});
}
setAudioBaby(updatedList)
});
} catch (error) {
console.log("error::", error);
}
}, []);
Final array should be like this:
[
{
lock: "active",
url: "item0.mp3",
},
{
lock: "active",
url: "item1.mp3",
},
{
lock: "active",
url: "item2.mp3",
},
]
I moved all ifs to inside of map function and everything is fine.
let updatedList = audioBaby.map((item) => {
if (item.url === 'item0.mp3' && response[0][1] === 'active') {
return { ...item, lock: 'active' }
}
if (item.url === 'item1.mp3' && response[1][1] === 'active') {
return { ...item, lock: 'active' }
}
if (item.url === 'item2.mp3' && response[2][1] === 'active') {
return { ...item, lock: 'active' }
}
return item
})
Related
What could be the possible reason? This is my Image and getRows code
getRows: (params: IServerSideGetRowsParams) => {
const { startRow, endRow, sortModel, filterModel } = params.request;
if (startRow === 0 && initialRender) {
getDashboardTableData({
variables: {
result: 'ProjectSummary',
startRow: startRow,
endRow: endRow,
tab: state.tab,
headerFilter: state.card,
filtergroup: JSON.stringify(state?.defaultFilter),
sortModel: JSON.stringify(sortModel?.length ? sortModel[0] : {}),
},
}).then((response) => {
if (response?.data) {
const { datarows, total } = JSON.parse(response?.data?.lpapqpprojectsumm.body);
if (response?.data?.lpapqpprojectsumm?.statusCode === '200') {
params?.success({
rowData: datarows,
rowCount: total,
});
}
} else {
params?.fail();
}
}).catch((error) => {
params?.fail();
});
}
I am developing my first application in vuejs and in the initial data upload in the script I need to modify the data I received from a call to the database.
Since I have modified the data it returns an error in the initial load of the page and after a few seconds it loads without problem.
I am trying to wrap this function in a settimeout but it returns an error in vuejs.
How can I apply this setTimeout?
here my script
<script>
export default {
data () {
return {
step: 1,
selected: 1
}
},
components: {
},
computed:{
selectedBasket() {
return !this.$store.getters.basket ? null : this.$store.getters.basket
},
items(){
return !this.$store.getters.items ? null : this.$store.getters.items
},
setTimeout(() => {
filteredEstimation(){
this.$store.getters.estimations.map(function(estimation) {
estimation.offers.map(function(offer) {
offer.name = offer.name.split(" ").reverse().slice(1).reverse().join(" ");
if (offer.name.includes("first")) {
offer.description = "first option";
}
if (offer.name.includes("second")) {
offer.description = "second option";
}
if (offer.name.includes("third")) {
offer.description = "third option";
}
});
});
return !this.$store.getters.estimations ? null : this.$store.getters.estimations.filter( item => item.id == this.selected )[0].offers
}, 700);
},
methods: {
getItemsName(item) {
if(item == 1){
return 'bag'
} else if(item == 2){
return 'paper'
} else {
return 'pen'
}
}
}
}
</script>
You're using that function inside the computed option, that's not allowed, you should define it in the mounted hook like :
<script>
export default {
data () {
return {
step: 1,
selected: 1
}
},
components: {
},
computed:{
selectedBasket() {
return !this.$store.getters.basket ? null : this.$store.getters.basket
},
items(){
return !this.$store.getters.items ? null : this.$store.getters.items
},
},
methods: {
getItemsName(item) {
if(item == 1){
return 'bag'
} else if(item == 2){
return 'paper'
} else {
return 'pen'
}
}
},
mounted(){
setTimeout(() => {
filteredEstimation(){
this.$store.getters.estimations.map(function(estimation) {
estimation.offers.map(function(offer) {
offer.name = offer.name.split(" ").reverse().slice(1).reverse().join(" ");
if (offer.name.includes("first")) {
offer.description = "first option";
}
if (offer.name.includes("second")) {
offer.description = "second option";
}
if (offer.name.includes("third")) {
offer.description = "third option";
}
});
});
return !this.$store.getters.estimations ? null : this.$store.getters.estimations.filter( item => item.id == this.selected )[0].offers
}, 700);
}
}
</script>
this is a part code file app.js
....
this.state = {
todoList: [
{ id: 1, name: "Khoa" },
{ id: 2, name: "Linh" },
{ id: 3, name: "Luc" },
],
inputText: "",
currentName: "",
todoSearch : []
};
}
....
handleSubmit = (e, inputRef) => {
const { todoList, currentName } = this.state;
if (inputRef.current.value.trim() === "")
alert("Hay nhap du lieu can input");
else {
if (currentName !== "") {
this.setState({
todoList : todoList.map(item => {
if(item.name === currentName) {
return {...item, name : inputRef.current.value}// error this code
}
}),
currentName : ''
})
} else {
const data = { id: todoList.length + 1, name: inputRef.current.value };
console.log("say hi");
this.setState({
todoList: [...todoList, data],
currentName : ''
});
}
}
};
.....
I want to update data unsatisfactorily item.name === currentName . Meaning replace name old of object in todoList equal new name is inputRef.current.value but not work. help me
Put else if the value doesn't match -
todoList : todoList.map(item => {
if(item.name === currentName) {
return {...item, name : inputRef.current.value}// error this code
}else{
return {...item}
})
When I try to return a specific property from my array, the terminal say:
TypeError: Cannot read property 'url' of undefined.
I want to search a specific element that valid this button.id === this.state.currentId control. So, when it's true I want to return element.buttonColor and, in the other method I want that its return 'element.url'. Why the first method: getCurrentBackgroundColor work and the second: getCurrentImage don't work?
this.state = {
currentId: null,
buttons: [
{
id: 0,
url: "./url1.jpg",
buttonColor: "#b2d8ca"
},
{
id: 1,
url: "./url2.jpg",
buttonColor: "#fef6bb"
}
],
};
getCurrentBackgroundColor = () => {
const currentButton = this.state.buttons.find((button) => {
return button.id === this.state.currentId;
});
return currentButton === undefined ? "" : currentButton.buttonColor;
};
getCurrentImage = () => {
const currentButton = this.state.buttons.find((button) => {
return button.id === this.state.currentId;
});
return currentButton === undefined ? "" : currentButton.url;
};
render() {
return (
<div className="App">
<LeftRight
backColor={this.getCurrentBackgroundColor()}
image={this.getCurrentImage()}
/>
</div>
}
//In the LEFTRIGHT class
<div
id="left"
style={{ backgroundColor: this.props.backColor }}
key={this.props.backColor}
>
<img src={this.props.image}/>
</div>
I noticed your current id is not set, you can change 'null' in the return sentence.
this.state = {
currentId: 0,
buttons: [
{
id: 0,
url: "./url1.jpg",
buttonColor: "#b2d8ca"
},
{
id: 1,
url: "./url2.jpg",
buttonColor: "#fef6bb"
}
],
};
getCurrentBackgroundColor = () => {
const currentButton = this.state.buttons.find((button) => {
return button.id === this.state.currentId;
});
return currentButton === undefined ? "" : currentButton.buttonColor;
};
getCurrentImage = () => {
const currentButton = this.state.buttons.find((button) => {
return button.id === this.state.currentId;
});
return currentButton === undefined ? "" : currentButton.url;
};
console.log("Background: ", getCurrentBackgroundColor())
console.log("Current Image: ", getCurrentImage())
this.state = {
currentId: 1,
buttons: [{
id: 0,
url: "./url1.jpg",
buttonColor: "#b2d8ca"
},
{
id: 1,
url: "./url2.jpg",
buttonColor: "#fef6bb"
}
],
};
getCurrentBackgroundColor = () => {
this.state.buttons.map((button) => {
if (this.state.currentId === button.id) return console.log(button.buttonColor)
});
};
getCurrentBackgroundColor()
I am using map function to iterate an object. but in one scenario i have to use nested map function. I try to add an value to an empty object inside an map function, but instead of adding values it replacing it. can anyone help me with this?
// object stores final results
let valid_data={}
//object to iterate
let test_cases = {
sample:
[ { test_case_no: 1,
test_case_description: 'user-status active - response 200',
value: 'active',
response_code: 200,
valid: 'yes' },
{ test_case_no: 2,
test_case_description: 'user-status inactive - response 200',
value: 'inactive',
response_code: 200,
valid: 'no' },
{ test_case_no: 3,
test_case_description: ' inappropriate user-status - response 400',
value: 'notAdmin',
response_code: 400,
valid: 'no' } ],
sample1: [ { obj1: [Array], obj2: [Array], test_case_no: 4 } ]
}
//my code to iterate an object
Object.entries(test_cases).map((property) => {
const field_name = property[0]
const field_definition = property[1]
Object.entries(field_definition).map((property) => {
if (property[1].valid != 'yes' && property[1].valid != 'no') {
Object.entries(field_definition).map((property) => {
Object.entries(property[1]).map((propertyy) => {
Object.entries(propertyy[1]).map((property) => {
nested_data = []
nested_value = {}
if (property[1].valid == 'yes') {
nested_value[propertyy[0]] = property[1].value
nested_data.push(Object.assign({}, nested_value))
valid_data[field_name] = (Object.assign({}, nested_value))
}
})
})
})
}
else if (property[1].valid == 'yes') {
valid_data[field_name] = property[1].value;
}
})
})
console.log(valid_data);
Actual result:
“{ sample: 'active',
sample1: { obj2: 2019-07-01T09:50:46.266Z } }”
Expected result:
“{ sample: 'active',
sample1: [{ obj1: 2019-07-01T09:50:46.266Z,obj2: 2019-07-01T09:50:46.266Z }] }”
Wrong var initialisation in your code.
Try this loop :
Object.entries(test_cases).map((property) => {
const field_name = property[0]
const field_definition = property[1]
Object.entries(field_definition).map((property) => {
if (property[1].valid != 'yes' && property[1].valid != 'no') {
nested_value = {}
Object.entries(property[1]).map((propertyy) => {
Object.entries(propertyy[1]).map((property) => {
if (property[1].valid == 'yes') {
nested_value[propertyy[0]] = property[1].value;
valid_data[field_name] = (Object.assign({},
nested_value))
}
})
})
} else if (property[1].valid == 'yes') {
valid_data[field_name] = property[1].value;
}
})
});
Working jsfiddle
Object.entries(test_cases).map((property) => {
const field_name = property[0]
const field_definition = property[1]
Object.entries(field_definition).map((property) => {
if (property[1].valid != 'yes' && property[1].valid != 'no') {
nested_data = []
nested_value = {}
Object.entries(property[1]).map((propertyy) => {
Object.entries(propertyy[1]).map((property) => {
if (property[1].valid == 'yes') {
nested_value[propertyy[0]] = property[1].value;
if(!nested_data.includes(nested_value)){
nested_data.push(nested_value)
valid_data[field_name] = nested_data
}
}
})
})
} else if (property[1].valid == 'yes') {
valid_data[field_name] = property[1].value;
}
})
})