Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 3 years ago.
Improve this question
I am learning react and get stuck in the following line of code:
const { favourites } = this.state
Can someone please help me?
that isn't React-specific, it is a JavaScript (ES6) feature called destructuring:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Object_destructuring
What this means is that the const favorites is equal to the value of favorites in the state of the component. So if the value of favorites is 22 in the state, the const favorite is equal to 22.
const { favourites } = this.state
is same as
const favourites = this.state.favourites
Also, an important note is that by using const, you're making the state.favorites prop read-only. Also, you can use it for any object. Let's say I had an employee object with employeeId, lastName, firstName props, etc. Let's say I get an array of employee objects, I can use this construct to greatly simplify the code.
render() {
const {UserName, EmailAddress, AccountCreated, PasswordChanged, AccountName,
Locked, Enabled} = this.props.ewdsUser;
return (
<tr>
<td>{UserName}</td>
<td>{EmailAddress}</td>
<td>{AccountCreated}</td>
<td>{PasswordChanged}</td>
<td>{Locked}</td>
<td>{Enabled}</td>
This prevents me from having to do this:
render() {
return (
<tr>
<td>{this.props.UserName}</td>
<td>{this.props.EmailAddress}</td>
<td>{this.props.AccountCreated}</td>
<td>{this.props.PasswordChanged}</td>
<td>{this.props.Locked}</td>
<td>{this.props.Enabled}</td>
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 23 days ago.
Improve this question
hello why i have typescript error?
LibraryContext.Provider is expecting libraryType.
While react query the default value is undefined.
So you may need to do something like this:
const defaultLibraryValue = {
name: '',
address: '',
phone: ''
//Add a default to each property of libraryType
} as libraryType;
<LibraryContext.Provider value ={{library: data === undefined ? defaultLibraryValue : data}}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I wanted to know how to add a field in a certain user uid
So I'd like to add another field like Address for the currentUser "Rowan Whitethorn". How can I do this?
Currently, i could add another field but it creates another documents.
const userRef = firestore.collection('users').doc(currentUser.uid);
async function addAddress() {
const res = await userRef.set({
'Address' : 'Ayala'
}, { merge : true});
}
Firestore documentation describes a feature "merge", where you would typically create a new doc with using ".set", but then pass a parameter "merge" which tells firebase not to overwrite your doc data, in your case it would be something like:
const userRef = db.collection('users').doc(doc_id);
const res = await userRef.set({
'some_new_field': 'value'
}, { merge: true });
Here's the link for their documentation, you will find a similar example under "merge": https://firebase.google.com/docs/firestore/manage-data/add-data
I am working through a simple logical problem, but I cannot seem to have things work smoothly. Let me share my most convincing code experiment and then I'll share some thoughts.
useEffect(() => {
firebase
.firestore()
.collection("someCollection")
.orderBy("date", "desc")
.onSnapshot(docs => {
let documents = []
if (canGetUpdatesFromFirestore.current) {
docs.forEach((doc) => {
documents.push(doc.data())
})
if(documents.length > 3) {
documents.splice(4, 0, {questionPostId: 0})
documents.splice(5, 0, {questionPostId: 1})
}
setAllQuestions(documents)
setUsers(documents)
}
})
if (searchValue.length > 2) {
canGetUpdatesFromFirestore.current = false;
functions.searchForSearchVal(searchValue, "Sexuality")
.then((result) => {
setAllQuestions(result);
})
} else {
canGetUpdatesFromFirestore.current = true
}
}, [searchValue])
function setUsers(docs){
let arrFinal = []
let copyOfAllQuestions = ""
for(let i = 0; i< docs.length; i++) {
console.log("HERE")
if (docs[i].postedBy) {
docs[i].ref.get().then(userFire => {
copyOfAllQuestions = {
...allQuestions,
...{hasPremium: userFire.data().hasPremium}
}
})
arrFinal.push(copyOfAllQuestions)
}
}
setAllQuestions(arrFinal)
}
Let me share some of my current state and what I am trying to accomplish.
I have a that display allQuestions. Each question data has a ref to its user document in firestore. For each question I need to check if that user hasPremium. How should I go about doing that the correct way?
The problem currently is that I can get the data from my Users collection through the ref, but I have to refresh my state in order for it all to show.
Could someone help me get on the right path / think correctly on this one please?
One approach that I put forward is to embrace data denormalization. That is, rather than putting references to other documents (Users) inside of the Questions document, put all the relevant user information directly into the Questions document.
This is antithetical to SQL database approaches, but that's okay because Firestore is "NoSQL". Embrace the anti-SQL-idity!!
Essentially, in your Question document you want to copy in whatever information is required in your app when working with a Question, and avoid doing "joins" by fetching other documents. You don't need to copy in all of the User document into a Question document - just the elements needed when your app is working with a Question.
For example, maybe in the question all you need is:
question: {
name: ...,
type: ...,
lastUpdated: ...,
postedBy: {
email: ...,
displayName: ...,
avatarUrl: ...,
hasPremium: true,
}
}
With data duplicated, you often need a mechanism to keep duplicate data up-to-date from its "source". So you might consider a Cloud Function trigger for onUpdate() of User documents, and when a relevant value is modified (email, displayName, avatarUrl, and/or hasPremium) then you would loop through all questions that are postedBy that user and update accordingly.
The rules-of-thumb here are:
all data needed for one screen/function in your app goes into a SINGLE document
NoSQL document stores are used where reads are frequent and writes are infrequent
NoSQL data stores (typically) do not have "joins" - so don't design your app to require them (which is what your code above is doing: joining Question and Users)
often you don't care about updating ALL instances of duplicated data (e.g. if a user updates their displayName today, should you update a Question they posted 3 years ago? -- different apps/business needs will give different answers)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I want to save houses in an array using AsyncStorage. Each array element represents a house Object. And each house object has a latitude, longitude and a house number. I am not sure how to go about representing this. It seems to me that AsyncStorage is not well-suited for saving dynamic objects that can be updated programmatically.
I want to be able to add more houses and delete some houses. Basically what I am trying to do is bookmark some houses and delete them from the bookmarks when the user clicks.
Can anyone help ?
AsyncStorage is absolutely perfect for this.
Starting with the structure of your houses, I would create an Array which stores objects representing an individual house.
const houses = [
{
number: 1,
latitude: 51.5033,
longitude: -0.119519
}
]
Saving to AsyncStorage
When you want to write your collection to AsyncStorage, you would do so like this:
AsyncStorage
.setItem('#houses', JSON.stringify(houses))
.then(houses => console.log(houses)
static setItem(key: string, value: string, callback?: ?(error: ?Error) => void)
You can also use async/await if your project is set up to support it.
Reading from AsyncStorage
Reading your collection back from AsyncStorage is simply done via:
AsyncStorage
.getItem('#houses')
.then(houses => console.log(JSON.parse(houses)))
You could set the response in your state, do as you please.
Deleting a specific house
This depends entirely on how you set your app up. Are you going to map through each house and create a list component for example?
(Sorry about losing the border on the right)
If so, you could:
houses.map(house => (
<View>
<Text>Number: {house.number}</Text>
<Text>Latitude: {house.latitude}</Text>
<Text>Longitude: {house.longitude</Text>
<Button onPress={() => this.deleteHouse(house.number)}/>
</View>
));
Then create a deleteHouse function which will handle it.
const deleteHouse = (number) => {
const { houses } = this.state; // Assuming you set state as previously mentioned
const newHouses = houses.filter((house) => house.number != number);
this.setState({houses: newHouses}, () => saveHouses);
}
And finally a saveHouses to sync it back to AsyncStorage. The function will clear AsyncStorage and then save the new houses.
const saveHouses = () => {
const { houses } = state;
AsyncStorage
.removeItem('#houses')
.then(() => {
AsyncStorage
.setItem('#houses', JSON.stringify(houses))
.then(houses => console.log(houses)
});
}
You need a Sqlite alternative like Realm, it's free, fast and easy to code, with this you will save tons of hours of work, also as you need, you can make queries, update and delete objects.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
This is my current object, Home refers to my import
import { Home } from '../home/home';
arr = [
{ name: "Home", root: "Home", icon: "calc" }
];
This is what i want to achieve:
import { Home } from '../home/home';
arr = [
{ name: "Home", root: Home, icon: "calc" }
];
Im getting a error because "Home" is a string. eval() works but i'm looking for a alternative
Working code:
for (var i = 0; i < arr.length; i++) {
arr[i].root = eval(arr[i].root);
}
It seems that this is your situation:
You are receiving a json from a server which has in certain fields names of classes that you need to use in runtime.
The names are strings and you need to get the classes they refer to.
You can indeed use eval as you used, but take into account that it is recommended to avoid using eval, especially when using it on data received from remote, for example from MDN:
eval() is a dangerous function, which executes the code it's passed
with the privileges of the caller. If you run eval() with a string
that could be affected by a malicious party, you may end up running
malicious code on the user's machine with the permissions of your
webpage / extension. More importantly, third party code can see the
scope in which eval() was invoked, which can lead to possible attacks
in ways to which the similar Function is not susceptible.
If you still want to use that, then go ahead, but an alternative is to have a registry of those classes:
const REGISTRY = {} as { [name: string]: { new(): any };
...
class Home { ... }
REGISTRY["Home"] = Home;
And then:
for (var i = 0; i < arr.length; i++) {
arr[i].root = REGISTRY[arr[i].root];
}
Another thing is that this approach creates coupling between the data which is returned from the server and the client side.
You always need to make sure that the class names you return in your json have a corresponding implementation on the client side.
If you rename the class in the client side you need to remember to change it on the server as well.
It's better to only return data and then have the client figure out by itself how to act and find the needed classes.