Firebase arrayUnion on nested array [duplicate] - javascript

I have a document in Firebase Firestore that is something like the below. The main point here is that I have an array called items with objects inside it:
{
name: 'Foo',
items: [
{
name: 'Bar',
meta: {
image: 'xyz.png',
description: 'hello world'
}
},
{
name: 'Rawr',
meta: {
image: 'abc.png',
description: 'hello tom'
}
}
]
}
I am trying to update a field inside the item array, under the meta object. For example items[0].meta.description from hello world to hello bar
Initially I attempted to do this:
const key = `items.${this.state.index}.meta.description`
const property = `hello bar`;
this.design.update({
[key]: property
})
.then(() => {
console.log("done")
})
.catch(function(error) {
message.error(error.message);
});
This didn't appear to work though, as it removed everything in the item index I wanted to modify, and just kept the description under the meta object
I am now trying the following which basically rewrites the whole meta object with the new data
const key = `items.${this.state.index}.meta`
const property = e.target.value;
let meta = this.state.meta;
meta[e.target.id] = property;
this.design.update({
[key]: meta
})
.then(() => {
this.setState({
[key]: meta
})
})
.catch(function(error) {
message.error(error.message);
});
Unfortunately though, this seems to turn my whole items array into an object that looks something like:
{
name: 'Foo',
items: {
0: {
name: 'Bar',
meta: {
image: 'xyz.png',
description: 'hello world'
}
},
1: {
name: 'Rawr',
meta: {
image: 'abc.png',
description: 'hello tom'
}
}
}
}
Any ideas how I can just update the content I want to?

Firestore doesn't have the ability to update an existing element in an indexed array. Your only array options for updates are described in the documentation - you can add a new element to the array ("arrayUnion") or remove an element ("arrayRemove").
As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely.

You can make a separate collection for that particular array, like this in this picture earlier I had different fields (no collections) of name, email and pages, And in this, I wanted to change the data of a specific page that is inside the array. For that, I made a different collection of pages with individual documents of each page having values of title description and content which can be mutated.

Related

Add data dynamically to an object recursively

Given the following code:
const data = {
name: 'product',
children: [
{ name: 'title' },
{ name: 'code' },
{ name: 'images', children: [{ name: 'image1' }, { name: 'image2' }] },
],
}
let result = {}
function resolveNodes(nodes, parentNode){
if(nodes.children){
parentNode = nodes.name;
result[parentNode] = {};
nodes.children.forEach(node => resolveNodes(node, parentNode));
}else{
result[parentNode][nodes.name] = nodes.name;
}
}
resolveNodes(data);
console.log(result);
Current output
{
product: {
title:"title",
code:"code"
},
images: {
image1:"image1",
image2:"image2"
}
}
Desired output:
{
product: {
title:"title",
code:"code",
images: {
image1:"image1",
image2:"image2"
}
}
}
I'm not sure how to recursively add a nested object within the parent (product) object. I've tried many things like passing the parent and the child to the function and from there try to work out the structure of the new object however it get very messy and I know is not the ideal way to do it.
This function will need to handle at least one extra layer of children but I've just added 2 to simplify the question.
What is the most ideal way to implement this?
You could take a recursive approach and have a look to children and get a combined object, otherwise just the name as value.
Instead of giving a simplified solution, let's have a closer look to the code.
resolveNodes = ({ name, children }) => ({ [name]: children
? Object.assign(...children.map(resolveNodes))
: name
})
The first part,
resolveNodes = ({ name, children }) =>
^^^^^^^^^^^^^^^^^^
the arguments of the function, contains a destructuring assignment, where an object is expected and from this object, the named properties are taken as own variables.
The following returned expression
resolveNodes = ({ name, children }) => ({
})
contains an object with a
vvvvvvv
resolveNodes = ({ name, children }) => ({ [name]:
})
computed property name, which takes the value of the variable as property name.
The following conditional (ternary) operator ?:
children
? Object.assign(...children.map(resolveNodes))
: name
checks children.
If this value is truthy, like an array, it evaluates the part after ? and if the value is falsy, the opposite of truthy, then it takes the expression after :.
In short, if no children, then take name as property value.
The part for truthy, if children exists,
Object.assign(...children.map(resolveNodes))
returns a single object with all children properties.
Object.assign(...children.map(resolveNodes))
^^^^^^^^^^^^^ create a single object
^^^ spread syntax
^^^^^^^^^^^ return all element by using
^^^^^^^^^^^^ the actual function again
This part is easier to understand if order of execution is followed.
children.map(resolveNodes)
the inner part with a mapping of children by calling resolveNodes returns an array of objects with a single property. It looks like this
[
{ title: 'title' },
{ code: 'code' },
{ images: // this looks different, because nested
{ // children are called first
image1: 'image1',
image2: 'image2'
}
}
]
and contains objects with a single property.
To get an single object with all properties of the array, Object.assign takes objects and combines all objects to one and replaces same properties in the target object with the latest following same named property. This is not the problem here, because all properties are different. Actually the problem is to take the array as parameters for calling the function.
This problem has two solutions, one is the old call of a function with Function#apply, like
Object.assign.apply(null, children.map(resolveNodes))
The other one and used
Object.assign(...children.map(resolveNodes))
is spread syntax ..., which takes an iterable and adds the items as parameters into the function call.
const
resolveNodes = ({ name, children }) => ({ [name]: children
? Object.assign(...children.map(resolveNodes))
: name
}),
data = { name: 'product', children: [{ name: 'title' }, { name: 'code' }, { name: 'images', children: [{ name: 'image1' }, { name: 'image2' }] }] },
result = resolveNodes(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Filtering away javascript objects into an array when using fetch

I have a react application, where I use the axios library, to get some values, and set them into an array of javascript objects in my state
componentDidMount(){
axios.get('http://localhost:8080/zoo/api/animals')
.then(res => this.setState({animals: res.data}))
}
Now I want to check if the objects, contains an Owner object, inside it, and filter out does that does,
First, I tried making a const, and then using the filter, to check if they contain the objects, and then set the state, but I can't save my values in a local variable
componentDidMount(){
const animals= [];
axios.get('http://localhost:8080/zoo/api/animals')
.then(res => animals=res.data)
console.log(animals) // logs empty array
console.log('mounted')
}
how can I make it so, that I can only get the animals that do NOT, have an owner object inside it?
Your animal array is empty in your second example because axios.get is asynchronous, what is in your then will be executed once the data is fetch, but the function will keep on going in the meantime.
To filter out your array, simply use filter right after fetching your data :
componentDidMount(){
axios.get('http://localhost:8080/zoo/api/animals')
.then(res => this.setState({animals: res.data.filter(animal => !animal.owner)}))
}
This function will filter out every animal object that does not have an owner property.
Working example :
const animals = [
{
name: 'Simba',
owner: {
some: 'stuff'
}
},
{
name: 1
}, ,
{
name: 2
}, ,
{
name: 3,
owner: {
some: 'stuff'
}
},
{
name: 'Bambi'
//status: 'dead'
}
]
console.log(animals.filter(animal => animal.owner))
EDIT: the answer was changed so that it only filters animals, that does not have an owner

Iterating trough array and sending http request dynamically

Okay, I have this array pokemonColor=['name1', 'name2', 'name3']. How can I iterate trough this array and dynamically send http request so I can update state like this below? Because this what I am trying does not work, it creates a JavaScript object, but too many of them...
This is what I want:
this.state.pokemon:[
{name: name1, img: img1},
{name: name2, img: img2},
{name: name3, img: img3}
]
And this is how I am trying:
componentDidUpdate() {
// console.log(this.state.pokemonColor);
this.state.pokemonColor.forEach(pok => {
axios.get(`https://pokeapi.co/api/v2/pokemon/${pok}/`).then(res => {
// console.log(res.data.sprites.front_shiny);
this.setState({
...this.state,
pokemon: {
name: res.data.name,
img: res.data.sprites.front_shiny
}
});
});
});
// console.log(this.state.pokemon);
}
First of all - this.state.pokemon = [...] mutates the state directly. Your app may crash or at least you will receive a long, red error in your console.
Secondly - you don't have to destructure state inside setState function.
Thirdly - with every axios get request, you are overwriting pokemon field in your state. I'd suggest you to keep your pokemons inside array.
this.setState((prevState) => ({
pokemon: [
...prevState.pokemon,
{
name: res.data.name,
img: res.data.sprites.front_shiny,
},
],
});
Then you will be able to access your pokemons by referencing to this.state.pokemons, which will be an array of objects.

Normalizr - is it a way to generate IDs for non-ids entity model?

I'm using normalizr util to process API response based on non-ids model. As I know, typically normalizr works with ids model, but maybe there is a some way to generate ids "on the go"?
My API response example:
```
// input data:
const inputData = {
doctors: [
{
name: Jon,
post: chief
},
{
name: Marta,
post: nurse
},
//....
}
// expected output data:
const outputData = {
entities: {
nameCards : {
uniqueID_0: { id: uniqueID_0, name: Jon, post: uniqueID_3 },
uniqueID_1: { id: uniqueID_1, name: Marta, post: uniqueID_4 }
},
positions: {
uniqueID_3: { id: uniqueID_3, post: chief },
uniqueID_4: { id: uniqueID_4, post: nurse }
}
},
result: uniqueID_0
}
```
P.S.
I heard from someone about generating IDs "by the hood" in normalizr for such cases as my, but I did found such solution.
As mentioned in this issue:
Normalizr is never going to be able to generate unique IDs for you. We
don't do any memoization or anything internally, as that would be
unnecessary for most people.
Your working solution is okay, but will fail if you receive one of
these entities again later from another API endpoint.
My recommendation would be to find something that's constant and
unique on your entities and use that as something to generate unique
IDs from.
And then, as mentioned in the docs, you need to set idAttribute to replace 'id' with another key:
const data = { id_str: '123', url: 'https://twitter.com', user: { id_str: '456', name: 'Jimmy' } };
const user = new schema.Entity('users', {}, { idAttribute: 'id_str' });
const tweet = new schema.Entity('tweets', { user: user }, {
idAttribute: 'id_str',
// Apply everything from entityB over entityA, except for "favorites"
mergeStrategy: (entityA, entityB) => ({
...entityA,
...entityB,
favorites: entityA.favorites
}),
// Remove the URL field from the entity
processStrategy: (entity) => omit(entity, 'url')
});
const normalizedData = normalize(data, tweet);
EDIT
You can always provide unique id's using external lib or by hand:
inputData.doctors = inputData.doctors.map((doc, idx) => ({
...doc,
id: `doctor_${idx}`
}))
Have a processStrategy which is basically a function and in that function assign your id's there, ie. value.id = uuid(). Visit the link below to see an example https://github.com/paularmstrong/normalizr/issues/256

Firestore Update single item in an array field

I have a document in Firebase Firestore that is something like the below. The main point here is that I have an array called items with objects inside it:
{
name: 'Foo',
items: [
{
name: 'Bar',
meta: {
image: 'xyz.png',
description: 'hello world'
}
},
{
name: 'Rawr',
meta: {
image: 'abc.png',
description: 'hello tom'
}
}
]
}
I am trying to update a field inside the item array, under the meta object. For example items[0].meta.description from hello world to hello bar
Initially I attempted to do this:
const key = `items.${this.state.index}.meta.description`
const property = `hello bar`;
this.design.update({
[key]: property
})
.then(() => {
console.log("done")
})
.catch(function(error) {
message.error(error.message);
});
This didn't appear to work though, as it removed everything in the item index I wanted to modify, and just kept the description under the meta object
I am now trying the following which basically rewrites the whole meta object with the new data
const key = `items.${this.state.index}.meta`
const property = e.target.value;
let meta = this.state.meta;
meta[e.target.id] = property;
this.design.update({
[key]: meta
})
.then(() => {
this.setState({
[key]: meta
})
})
.catch(function(error) {
message.error(error.message);
});
Unfortunately though, this seems to turn my whole items array into an object that looks something like:
{
name: 'Foo',
items: {
0: {
name: 'Bar',
meta: {
image: 'xyz.png',
description: 'hello world'
}
},
1: {
name: 'Rawr',
meta: {
image: 'abc.png',
description: 'hello tom'
}
}
}
}
Any ideas how I can just update the content I want to?
Firestore doesn't have the ability to update an existing element in an indexed array. Your only array options for updates are described in the documentation - you can add a new element to the array ("arrayUnion") or remove an element ("arrayRemove").
As an alternative, you can read the entire array out of the document, make modifications to it in memory, then update the modified array field entirely.
You can make a separate collection for that particular array, like this in this picture earlier I had different fields (no collections) of name, email and pages, And in this, I wanted to change the data of a specific page that is inside the array. For that, I made a different collection of pages with individual documents of each page having values of title description and content which can be mutated.

Categories

Resources