You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: MongoDB/populate-method-mongoose-referencing-other-model.md
+18-13
Original file line number
Diff line number
Diff line change
@@ -1,3 +1,5 @@
1
+
##### `.populate()` is a way to populate referenced subdocuments in any schema.
2
+
1
3
Lets take an example of a social network, one collection for users, and one for posts. In my research before doing any coding, I stumbled upon `Model.populate()`, a Mongoose method that you can use to essentially link documents across collections.
2
4
3
5
### Step 1: Make your schemas
@@ -32,6 +34,8 @@ module.exports = {
32
34
};
33
35
```
34
36
37
+
### Most simply - If you run this query: Post.find({}).populate('user').exec(callback), Mongoose will look at the field user in the post, see that it has a ref to the User model, and find that user by its \_id
38
+
35
39
This tells Mongoose “Hey, I’m gonna be referencing other documents from other collections”. The next part of that property is the ref (Post or User in the above code). The ref tells Mongoose “Those docs are going to be in the Post or User collection.”
36
40
37
41
So in our User schema, we reference the Post collection, because we want the user to be tied to the things they post, and we want to be able to easily access those posts without having to create more queries.
@@ -149,25 +153,26 @@ And in my Profile routes I have the following API endpoint
149
153
150
154
```js
151
155
router.get(
152
-
'/',
153
-
passport.authenticate('jwt', { session:false }),
156
+
"/",
157
+
passport.authenticate("jwt", { session:false }),
154
158
(req, res) => {
155
159
consterrors= {}; // just like in user route, I want to append to the errors object for any actual errors that will be generated. And returning that object for the error case
156
160
157
161
Profile.findOne({ user:req.user.id })
158
-
.populate('user', ['name', 'avatar'])
162
+
.populate("user", ["name", "avatar"])
159
163
.then(profile=> {
160
164
if (!profile) {
161
-
errors.noprofile='There is not profile for this user';
165
+
errors.noprofile="There is not profile for this user";
162
166
returnres.status(404).json(errors);
163
167
}
164
168
res.json(profile);
165
169
})
166
170
.catch(err=>res.status(404).json(err));
167
171
}
168
-
)
172
+
);
169
173
```
170
-
In the above A) I am populating my user's profile using the query builder. http://mongoosejs.com/docs/populate.html#population
174
+
175
+
In the above A) I am populating my user's profile using the query builder. http://mongoosejs.com/docs/populate.html#population
171
176
172
177
B) The first parameter of .populate() is the model you wish to use for population. If not specified, populate will look up the model by the name in the Schema's 'ref' field.
@@ -177,22 +182,22 @@ C) The second parameter to .populate() is the Field selection for the population
177
182
D) Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). So, when I do the below
178
183
179
184
Profile.findOne({ user: req.user.id })
180
-
.populate('user', ['name', 'avatar'])
185
+
.populate('user', ['name', 'avatar'])
181
186
182
-
Populated paths are no longer set to their original _id , their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.
187
+
Populated paths are no longer set to their original \_id , their value is replaced with the mongoose document returned from the database by performing a separate query before returning the results.
183
188
(http://mongoosejs.com/docs/populate.html)
184
189
185
190
E) .populate() needs a query to attach itself to, so we are using Profile.findOne() to find a profile who matches the id I provide in the argument. This returns our user document. This is when .populate() takes over.
186
191
187
-
F) Flow of .populate() -> After findOne() finds the req.user.id and assigns it to the variable 'user' > .populate() is called on user, it will go to the appropriate collection (user model in this case) , search for that _ids, and return my user with 'name' and 'avatar'
192
+
F) Flow of .populate() -> After findOne() finds the req.user.id and assigns it to the variable 'user' > .populate() is called on user, it will go to the appropriate collection (user model in this case) , search for that \_ids, and return my user with 'name' and 'avatar'
188
193
189
194
G) Why I can fetch user's model data with below line from profile route.
190
195
191
-
Profile.findOne({ user: req.user.id })
192
-
.populate('user', ['name', 'avatar'])
196
+
Profile.findOne({ user: req.user.id })
197
+
.populate('user', ['name', 'avatar'])
198
+
199
+
Because - In Profile model, I have the the 'user' property as ObjectId
193
200
194
-
Because - In Profile model, I have the the 'user' property as ObjectId
Copy file name to clipboardExpand all lines: React/HOC.md
-1
Original file line number
Diff line number
Diff line change
@@ -1,4 +1,3 @@
1
-
Intro
2
1
To put it simply, a higher-order component is a function, that takes a component and returns a new component. I like to think of them as parameterized components. Many times I find myself creating several components with very similar logic, with only 1 or 2 changes. Once I find a use case like this, it’s very simple to abstract the shared logic, and put the logic that changes into parameters.
3
2
4
3
You can read more about HOCs here, in the official React docs. Since components are just functions and HOCs are just functions that return other functions, we can use functional concepts to chain them using utilities methods such as compose, which is provided by many libraries (it's included in Redux!).
Copy file name to clipboardExpand all lines: React/context-api-basics.md
+24-31
Original file line number
Diff line number
Diff line change
@@ -16,52 +16,39 @@ Material UI provides a snackbar component which is great for these types of mess
16
16
17
17
Many apps need to trigger messages from dozens of different components. The React Context API makes it dead simple to provide all components access to a shared snackbar so they can trigger these messages without needing to implement separate components for each message.
18
18
19
-
20
19
### [How Do I Use Context?](https://hackernoon.com/how-do-i-use-react-context-3eeb879169a2)
21
20
22
21
[the codesandbox for this code](https://codesandbox.io/s/04l03y3q9v)
23
22
24
23
Prop Drilling
25
24
I’ve built an application that stores a family’s last name in a <Grandmother /> component. The <Child /> component than displays the last name.
26
25
27
-
28
26
```js
29
-
constApp= () =><Grandmother />
27
+
constApp= () =><Grandmother />;
30
28
31
29
classGrandmotherextendsReact.Component {
32
30
state = {
33
31
lastName:"Sanchez"
34
-
}
32
+
};
35
33
36
34
render() {
37
-
return<Mother lastName={this.state.lastName} />
35
+
return<Mother lastName={this.state.lastName} />;
38
36
}
39
37
}
40
38
41
39
constMother= ({ lastName }) => {
42
-
return<Child lastName={lastName} />
43
-
}
40
+
return<Child lastName={lastName} />;
41
+
};
44
42
45
43
constChild= ({ lastName }) => {
46
-
return<p>{lastName}</p>
47
-
}
44
+
return<p>{lastName}</p>;
45
+
};
48
46
```
49
47
50
48
### Context
51
49
52
50
We can refactor this example to use Context instead. Using Context means we don’t need to pass the lastName through the <Mother /> component. We circumvent components that don’t need to know the lastName property, and share that state only with components that need to know it.
Now, we have wrapped the <Mother /> component with <FamilyProvider /> because it contains <Child /> which is the component that needs access to the lastName prop.
120
108
121
109
```js
@@ -130,21 +118,25 @@ To actually have access to the lastName, we have also wrapped the <p> tag on lin
130
118
131
119
### Let’s dig a bit deeper into <FamilyConsumer />!
132
120
133
-
At first, it might look a bit confusing if you aren’t familiar with the render prop pattern, but with a bit of explanation I think you might find that it’s a fairly straightforward implementation. You don’t need to know how to build a render prop to use Context, but it’s a really powerful abstraction!
121
+
At first, it might look a bit confusing if you aren’t familiar with the **[render prop](https://reactjs.org/docs/render-props.html)** pattern, but with a bit of explanation I think you might find that it’s a fairly straightforward implementation. You don’t need to know how to build a render prop to use Context, but it’s a really powerful abstraction!
134
122
135
123
### What’s a Render Prop?
136
124
137
-
A render prop is a way of writing components in React so that they are reusable, and can take n number of children of any type. Render props appear in a couple of different disguises. Context implements a Function as a Child Pattern, which is just a render prop called children.
125
+
The term **“render prop”** refers to a technique for sharing code between React components using a prop whose value is a function.
126
+
127
+
A **render prop** is a way of writing components in React so that they are reusable, and can take n number of children of any type. Render props appear in a couple of different disguises. Context implements a Function as a Child Pattern, which is just a render prop called children.
138
128
139
129
```js
140
130
constChild= () => {
141
131
// Family Consumer uses the
142
132
// Function as a Child pattern
143
-
return<FamilyConsumer>
144
-
// context is the object with lastName
145
-
// on it. It gets passed as an argument
146
-
{context=><p>{context}</p>}
147
-
</FamilyConsumer>;
133
+
return (
134
+
<FamilyConsumer>
135
+
// context is the object with lastName // on it. It gets passed as an
136
+
argument
137
+
{context=><p>{context}</p>}
138
+
</FamilyConsumer>
139
+
);
148
140
};
149
141
```
150
142
@@ -153,11 +145,12 @@ const Child = () => {
153
145
Ultimately, Context is a great tool to add to your React toolbox. Use it when you find prop drilling has become too complex, but your application isn’t large enough to warrant a third-party solution like MobX or redux.
I would recommend reaching for Context when you find yourself passing props down through three or more levels in your component tree. You might notice that you have renamed your props, making it challenging to determine the data’s origin. You might consider implementing context if a bunch of your components know about irrelevant data.
### you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
4
+
5
+
[https://reactjs.org/docs/hooks-effect.html](https://reactjs.org/docs/hooks-effect.html) - The Effect Hook lets you perform side effects in function components. Data fetching, setting up a subscription, and manually changing the DOM in React components are all examples of side effects.
6
+
7
+
In React class components, the render method itself shouldn’t cause side effects. It would be too early — we typically want to perform our effects after React has updated the DOM.
8
+
9
+
This is why in React classes, we put side effects into componentDidMount and componentDidUpdate.
10
+
11
+
## Effects Without Cleanup {#effects-without-cleanup}
12
+
13
+
Sometimes, we want to **run some additional code after React has updated the DOM.** Network requests, manual DOM mutations, and logging are common examples of effects that don't require a cleanup. We say that because we can run them and immediately forget about them. Let's compare how classes and Hooks let us express such side effects.
14
+
15
+
### Example Using Classes {#example-using-classes}
16
+
17
+
In React class components, the `render` method itself shouldn't cause side effects. It would be too early -- we typically want to perform our effects _after_ React has updated the DOM.
18
+
This is why in React classes, we put side effects into `componentDidMount` and `componentDidUpdate`. Coming back to our example, here is a React counter class component that updates the document title right after React makes changes to the DOM:
Note how **we have to duplicate the code between these two lifecycle methods in class.**
52
+
This is because in many cases we want to perform the same side effect regardless of whether the component just mounted, or if it has been updated. Conceptually, we want it to happen after every render -- but React class components don't have a method like this. We could extract a separate method but we would still have to call it in two places.
53
+
Now let's see how we can do the same with the `useEffect` Hook.
54
+
55
+
### Example Using Hooks {#example-using-hooks}
56
+
57
+
We've already seen this example at the top of this page, but let's take a closer look at it:
58
+
59
+
```js{1,6-8}
60
+
import React, { useState, useEffect } from "react";
**What does `useEffect` do?** By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we'll refer to it as our "effect"), and call it later after performing the DOM updates. In this effect, we set the document title, but we could also perform data fetching or call some other imperative API.
76
+
**Why is `useEffect` called inside a component?** Placing `useEffect` inside the component lets us access the `count` state variable (or any props) right from the effect. We don't need a special API to read it -- it's already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a solution.
77
+
**Does `useEffect` run after every render?** Yes! By default, it runs both after the first render _and_ after every update. (We will later talk about [how to customize this](#tip-optimizing-performance-by-skipping-effects).) Instead of thinking in terms of "mounting" and "updating", you might find it easier to think that effects happen "after render". React guarantees the DOM has been updated by the time it runs the effects.
Copy file name to clipboardExpand all lines: Redux/Store.md
+1-1
Original file line number
Diff line number
Diff line change
@@ -8,4 +8,4 @@ A store is not a class. It's just an object with a few methods on it. To create
8
8
9
9
Check my working file - [https://github.com/rohan-paul/React-snippets/blob/master/redux-show-list-of-micro-blog-posts/src/store.js](https://github.com/rohan-paul/React-snippets/blob/master/redux-show-list-of-micro-blog-posts/src/store.js)
10
10
11
-
A store holds the whole state tree of my application. The only way to change the state inside it is to dispatch an action on it. A store is not a class. It's just an object with a few methods on it. To create it, pass your root reducing function to createStore.
11
+
A store holds the whole state tree of my application. The only way to change the state inside it is to dispatch an action on it. A store is not a class. It's just an object with a few methods on it. To create it, pass your root reducing function to createStore.****
0 commit comments