Video Transcript
Today I'll give you a brief introduction to the React.js library to build user interfaces
on the front end.
I will use this code sandbox environment and I went to code sandbox.io slash s slash react
dash new to spawn this environment.
Okay.
So what is React?
Very popular today.
Basically it's a library which means code that somebody else wrote to build user interfaces.
People kind of got tired of doing HTML, CSS, and JavaScript in a certain way because the
code can get very messy over time, especially as you're grabbing elements, finding elements
in the document.
So somebody thought of the idea why not we declare what we want to see, just like we
do HTML, and we let the library take care of updating the DOM for us instead of us having
to manually, programmatically make calls to manipulate the DOM.
That is, okay, if you create a new thing, you would have to first select the element and
then you have to get the data and create the element, change the text content, maybe add
some classes, and do all this stuff and then you inject that element into the document
object model, wherever you want that to be, and then you've got to take care of events.
What if there's event delegation, all that stuff?
So React is just, okay, this is just too much.
How about we just declare what we want to see, like a template, and then we take care
of all the rest for you.
I don't have to worry about all this manual stuff.
Okay.
Enough of that talk.
So React has got so popular today, you can even use it for mobile with React Native.
You can write actual mobile apps with just JavaScript language, and it can even do React
VR and all this other stuff.
All right.
So let's again, the link I'm pasting to the Zoom chat.
So today, I want to give you an example of making blog posts.
Imagine you have a blog and you have to show some posts.
So that's the example I'm going to use.
Now, what is React and how do we go about that?
So basically, we have an index.html page here, and you can notice the body, there's pretty
much nothing.
And all you do is you create a div, and you give it some sort of way to find this element
could be by DID.
Document get element by D. Okay.
So now, what this is doing is basically creating a single-page application.
What somebody's requesting is something.
What is this?
Could you explain in the chat why you're requesting that?
Otherwise, I'm going to think you are not in good faith.
Anyway.
So what's happened is basically, React is a single-page application in the sense that
you're going to get the HTML file pretty much empty, and then the client side is going to
build a page according to the template that you define in the React files.
So let's see here.
So basically, index.js under source, this will basically get the element by ID and inject
and render to React app right there.
Now the app, this thing is defined in app.js here.
And this is basically a function, JavaScript function named app, and returns a template
for what we want to see.
So React is just like this.
So basically, we're going to work with what's called components.
So if you come from the world of HTML, we think about elements, right?
A tag of paragraph, a p tag, that's an element paragraph.
In this case, we've got a div, one, each two, and so on.
So basically, in React world, we call those elements components.
And then when we talk about their attributes in HTML, in React, we call them properties.
For example, the class name property here.
So all we do in React is we define these functions.
And we usually capitalize the first letter.
So this is a nap component.
And then from the function, we are going to return a template for what looks like HTML.
Now HTML is not actually this thing.
This thing is called JSX, which is basically a JavaScript function calls to react dot create
element.
So it's just a synthetic sugar, but to make us believe it's HTML, but it's actually not.
So if you were to write this in actual JavaScript, it would be pretty much you'd have to do React,
create element, and then you're going to do the div, and then you're going to add a class
name basically like this.
And then you've got to add the children, and so on and so on.
So it's very tedious to do it programmatically like that.
So that's why that declarative way was created.
If you're more interested in that, go ahead, look up Babel, and it does a translation for
you to see.
In any case, so just create a function, give the first name, capitalize, and then return
the template for what you want to see.
For example, hello code sandbox, I can change this, and you will see there, there.
You see that changed real time on the right-hand side because we got a preview.
Okay.
Now everybody got that very easy.
So basically I could write whatever I want, you could delete that, start writing paragraph,
hello there, oops.
So if you know HTML, it's very easy.
Now there's some differences between HTML and this, and the first one you got to see
is class name.
Notice in HTML is just class, but in React you had to say class name.
Now the reason for that is JavaScript, the programming language, a class is a reserve
keyword, so you can define a class which is a blueprint for an object.
So that's why I got to use class name here.
Otherwise I'm going to conflict with the reserve word.
Anyway, got that.
So let's talk about how to create a blog post here.
Maybe I want to create a listing.
So what I'm going to do is remove all the styles, just have a div, and I'm just going
to add here maybe h1, blog posts.
And then let's just define what we would like to see for a blog post.
Maybe I can say post list, in a div of the class post list.
And then one of the divs would be a container for the blog post.
Maybe I could have an image source I'm going to define later.
One thing to notice here, if you have images, you must close the tag.
You know in HTML self-closing, but this will not work in React.
So you can either close it like this, or you can add the slash here to auto close.
Okay, I usually like to add a space there.
Anyway, there's an image, let's add a div, maybe add the blog post title.
We're just adding some dummy data there, just for the sake of having something to show.
Now the image, I just want to show some dummy image.
I have this website here, that's very nice, called fixum.photos.
And pretty much you can copy this link and change the dimensions with slash the height
there.
So that's what I did.
Basically I did this one here.
So let me paste to the zoom chat.
Basically this link slash 800 width slash 450 height.
That's what it does.
You can generate this image like so, okay?
So I'm just going to go back to my window and for the source of the image, I'm going
to paste that.
And you can see there's a huge image there.
So probably want to add some width attributes for now.
Let's see if I do 200.
And the height will adjust the curling to the aspect ratio.
Maybe that's okay, just 200 for starters.
So if you want to style this with CSS in React world.
So what you do is you would import some CSS file like this.
So you say import and then you give the path to the file under quotes.
In this case, we already had the file styles.css.
So if you open that, let me see if you can open downward view, appearance, where is that?
In a position.
This is a little bit different from the visual studio code on desktop.
Oh, here.
Editor layout.
There you go.
I just want to open it down here so I can have both.
Okay.
So this is where you define your CSS just like normal.
You would do with normal HTML CSS except you don't have the link tag here because everything
is taken care of you.
By the way, I think this environment is using create React app with React scripts.
Yes.
So that's why that's how it's all taken care of for you.
And I think behind the scenes, it's using what's called Webpack to bundle all of this
if you're interested in the behind the scenes.
Anyway, going back here, I want to style this just a little bit better.
Maybe I want to make this line eight, just a post list item.
So I would create a post list item selector for the class.
The dot is class if you're new to CSS.
And I just want to add some borders, let me do a few pixel solid black and you see add
a border there.
Okay, I want to make this display flex so that they flow from left to right.
And I think for the item, that's enough.
Now this this part here I don't like.
So I'm going to put a container there, and like this, and then add a class, maybe post
list item, I don't know, data, post list item data, not going to spend a lot of time thinking
about CSS because we want to focus more on React.
So you're free, feel free to change to whatever you want.
Okay.
So just like that, actually just adding the div would make it without any flex direction
route.
Anyway, you can style that if you want.
And oh, yeah, sorry.
Good question.
I have to add class name.
You're right, otherwise it's going to complain.
Do you need to use class name only an apparent tag or can class mean child tags?
No, so you always have to use class name.
And I think the reason this worked is because you can have a plugin to Webpack that it can
actually let you write class just like this without being class name.
But if you don't have that, you have to always say class name.
That's the proper way to do it in the React world, okay?
So thank you for that.
And we do it out of habits, right?
So, okay.
So I think that's enough.
So this is what I wanted to look like.
So essentially I would copy this and paste it like this so I'd have multiple posts.
And then if I want to change the distance between them, I usually like to look to the
parent container and add some CSS targeting it like this.
If you have an element under the element with class dot post list, I want the element
that has the class post list item to have a margin bottom of 16.
That way, every one of them at the bottom will have 16.
If you want more, you can add here like 32, either way.
Okay, what else?
I think that's good enough.
For the data, if you want to add a margin left so it doesn't get glued to the image,
maybe you can do that.
And then some padding, or maybe just add padding like this, and it becomes like that.
Anyway, I think we're good CSS, okay.
So that's pretty much how you'd write things, just like HTML, but remember just class name
and some tags like image need to be closed.
You cannot have self-closing, so add that thing.
I don't like this thing, I want to change to word wrap, so I don't have to scroll horizontally.
So I'm going to use this option, word wrap, okay, so I don't have to scroll.
There you go.
Okay, now let's do a little bit better.
This is just dummy data.
In an actual thing, this data would come from a backend server, and then we would get an
array of objects that would represent each of these posts.
And then in React, we would actually create all of these divs dynamically.
We would not declare them like this because we don't know exactly ahead of time what posts
there are.
So let's do a little better.
So I'm going to extract all this data into an object here, an array of average actually,
let's call it posts.
So an array, okay, square brackets, and I'm going to represent each of them with an object,
so curly brace, give it a unique identifier like ID, which is a number type.
And we're going to have the title, and we got the body, like this.
And you can repeat three times just for the sake of dummy data.
And if you want to add a distinguished number here, you can do this for the sake of differentiating
them.
This looks a lot more like what we would get from the server, so we would have to use
this variable post to create all of these divs.
So we don't want to do the repetition here.
I only have to have one of them, and then what I'm going to do is generate this artificially.
So what we usually do is we take the array, and we map.
Basically for every element that's an object, I'm going to generate this div.
And the way we usually do that is with this function called map, and it can pass a function
as the argument.
It could be a function keyword or arrow function, doesn't matter.
And the argument is the element itself, I'm going to call it posts.
And for the sake of being explicit, so you know what's going on, this function, for every
object, every element in the list, we will receive the post object like this one.
And then we can use that to return an actual div like this.
So I'm going to move this inside.
By the way, I use alt, up, up, to move it inside, and tab, tab to indent, like that.
You can see it's still working, but the post title and body is not correct.
So we would have to substitute these with the actual post title from the variable post.
So how do we do that?
Well, somebody might say, well, it's an object, so post.title, right?
Well, it will literally show post.title.
So if you want to actually substitute the value referenced by that, you've got to have
the curly brace surrounding it.
That way I can see post title one appear, two and three there, okay?
So it's basically iterating over that array.
And for each element, it generates a new one, that's this div.
And at the end, we're going to get an array.
So React, when it sees there's an array, it will know to render each one of them.
Okay, let's do the same for post body, post.body under curly brace.
Now they all appear.
And on and on.
I'm not going to do the image because for the sake of time, basically this image
would probably be in this object, like image URL, and then you put the source here.
But I'll keep a dummy image there.
Okay, so this is how you dynamically generate components.
If you have any questions, let me know.
Okay, so let's say I want, so what do you want to do now?
Do you want to add a new post or you want to fetch?
I think fetching the data from the backend might be a little bit too hard right now.
Somebody asked, can we extract components in their own classes?
Did you mean functions?
Yes.
Yes, you can.
That's a good question.
That's maybe it's a good practice.
Let's say this component here gets way too complex.
And we want to isolate the logic into a different place because just too hard to read all the code is just too long.
Obviously, right now it isn't, but let's imagine.
So somebody has just asked about, can we extract this to a different component?
Yes, that's what we usually do.
So to create another component, you're going to go here outside, create a function.
Let's call it post list item and then parentheses.
This function will return the template for that post list item, which is this thing here.
I'm just going to copy for now.
Okay.
So I copy the return value from the callback to map.
I'm going to paste it here like that.
Okay.
Now, how do we use this component that we created here?
Well, it's easy.
It's just like HTML.
You put a tag, give the component name with this case post list item.
Remember post list item.
And that's it.
If you want to close it like HTML, you do it like this.
All right.
So that's how we do it.
Now, if it's self-closing, you don't want to pass anything down between the tags.
That's usually what we call the children.
You can just auto close like this.
Now it's going to give us a problem, right?
Because it doesn't know what post is when we go back to the definition of post list item.
What is post?
What is this?
I don't know what it is.
That's why it's complaining here.
This is how you debug.
You see, post is not defined.
Now, we have to pass down the information to the component.
And the way we do that is via what we call props, which is basically HTML attributes.
So if you go back to this instance in line 39, let's pass down the post as an argument here,
via the attribute, how we call an HTML, which is actually a prop or property in React.
So we can just pass the post like that.
So this value here goes here.
And this value here will appear as the props dot post in this definition.
You can call this whatever, okay?
You can call it whatever like this.
And if you go up there to post list item, you can accept the props like argument there.
And you can say props dot whatever.
And that will give you that post object.
Obviously, I don't want to name it whatever because that's not very descriptive.
I'm going to call it post, okay?
So I'm going to go back there and change it to post.
I just wanted to, I just did that because these have the same names.
I didn't want to confuse you.
I want you to know exactly this is that.
And this is just the props dot post that will appear.
Anyway, you can call this props dot post.
You can call this props dot post.
And that way you access from what was passed down to this component.
Okay.
You might also see this destructuring syntax where people like putting like this.
And then it creates a variable extracted from the props.
That's totally fine too, okay?
But I think it's for us beginners, it's better we be explicit so we know where things are coming from.
Okay.
Now, that's how you do the different components.
Now, somebody mentioned classes.
So I just want to point out that in the beginning of React,
we used to write components with a class definition,
and then we would instantiate them as objects of the class.
Now, it's more encouraged now these days to create functional components,
meaning they define these functions very simply.
Now, whether you like it or not, it's another debate.
So going forward, they just encourage you to create functions.
All right.
Now, going a step further, you could actually,
people like to extract these components to a separate file.
So you could also do that.
Let me teach you how.
So let's create a folder here to be organized and call it components.
And in this components directory, I'll create a new file that I'll call postlistitem.js.
You might also see people using the extension JSX because it's using JSX.
That's fine as well, okay?
And if you're using TypeScript, you're going to see TSX.
Anyway, I'm just going to use JS because it's simple.
And then what we're going to do is go back to app and cut the definition of this function, postlistitem.
And then go to postlistitem and paste it here and fix the indentation.
I usually like four.
Let me see.
Sorry, two spaces.
There you go.
Now, this component, how do we use it from a separate file?
Well, we got to import it.
So from app point of view, if we're using this, it doesn't know what it is.
So we got to import at the top postlistitem from someplace.
So dot slash the path to that, which is dot slash components slash postlistitem.
Now, the dot means current directory.
So it's sort of a relative path.
Okay, now the other problem is from the point of view of the component itself in a separate file,
this one app doesn't have access to it.
So to make it available there, you got to do export default before the function definition.
You can also do it outside afterward like this if you repeat the name.
Either way, okay.
By the way, if you're doing react outside of this environment, you might run into the problem where react is not defined because you're using JSX.
So you would do import react from react usually at the top of every component.
And I think the reason this works without typing it's because there's probably a plugin somewhere that automatically adds that for us during the translation.
Okay, so that's how you make your own component.
Okay, now let's go back to what we were doing before.
I'm going to go one step further and make and make us add a new post.
How do we add a new post?
So for the sake of simplicity, I'm going to have it in the same page, right?
Same view.
Usually you would click somewhere and it will go to a totally different view where you have a form to create the post, whatever.
We don't have time for that.
So I'm just going to put it here.
So I'm going to create a form.
Okay.
And in this form, I just want to put some, let's see, input type text name.
I'm going to call it title.
And remember, react world, we cannot auto like have self closed like this.
We got to add the slash.
All right.
And before I move on, I think something about the map here, you might also see some warning in the console.
I don't know where my console is here.
I don't know why it's not.
Let me see.
I think I can go here toggle tasks in terminal.
Yeah.
Anyway, let me try DevTools F12 console.
Let me see here.
Yeah, this one.
This is what I wanted to show you.
This warning, you're going to see this a lot.
You never call map.
And you return something that's calling map in a react component to generate dynamically is going to play about not having the key prop.
So this is not a big deal, but all you have to do is go to whatever you're mapping to the return value and add a key.
That's something unique, like the post.id.
And last resort is the index.
Okay.
But people don't want to use index, but this is more about if you have something like it's being sorted, but we don't have the use case.
It doesn't really matter.
So that's to make it stop complaining.
And if you do that, I don't think if I press click here and press F12, I don't think we have that anymore.
Let me see refresh.
Yeah.
I did encounter two children same key.
That's because I put the ID the same.
It's not unique.
So I got to change it to two and three.
Let's try again.
Trash that.
There you go.
I think no more errors.
It's no big deal there, but we always going to have that warning.
Okay.
Going back to the form.
Let's add a label.
And I want to say title and not going to add any more extra attributes.
I want to be quick.
Make a div here.
You can make it pretty later if you want.
Let's just do the title for the sake of time and add a div input type submit value create post.
And you have to self close like this.
And there you go.
Now, if I type anything here, I want to click create post.
So the form will be submitted.
And then I want to add to the list here.
How do we do that?
Okay.
Let's first deal with the events.
So when you submit the form, you can handle the on submit event.
Now you can go to the form tag and add on submit.
If you do HTML, it's like this.
And they would call a function on create post or whatever you want to call it.
Let's call it an on submit.
And you would do it like this, right?
That's the HTML way in react way.
You've got to change a little bit.
You have to put a camel case here.
So the ass is capitalized and then you cannot just call the function like that.
You actually have to pass the definition of a function with the curly brace.
Now in a react world, when you have attributes like HTML, these props, the syntax is always the name equals sign and curly brace and then whatever.
That's the syntax.
Now, if you do have a string as the value within the curly brace, it's optional to have the curly brace.
So that's why I didn't type type text here like that, but it's the same.
Okay.
So you cannot meet them if it only a string.
Now on submit is not defined.
That's why it's complaining.
Let's go here before return.
And we're going to declare a function on submit.
There's an event parameter.
And we're going to call event dot prevent default.
So the form is not actually submitted the traditional way because I don't want to go back to a server somewhere.
I just want to keep staying the same place, not do anything.
Okay.
So when I click create post, it's going to fire up this function on submit.
And if you notice, I define a function inside a function.
Okay.
I know I did that.
That's intentional.
All right.
So how do we access what the user type?
How do we inject into the post?
That's the big problem here.
If I just do, for example, post dot push some new object for with title, whatever, it's not going to work.
If I try that, let me see.
Nothing happens.
Why?
Because react doesn't know about this.
It doesn't know that this array just got pushed.
It's not tracking it.
Remember, when we use react, react is taking care of updating the DOM for us.
So we just declare, okay, react, I want to see this.
And then you are in charge to make sure the actual DOM, the document live is reflecting the structure that I defined.
But when I change post dot push here, react doesn't know about it, doesn't react to it.
So you have to tell react, hey, I want you to track this array of posts.
And whenever I push, the post will change.
Therefore, you should be re-rendering this component.
Now, to do that, we use state, okay, the react state.
In the past, we would just define an instance variable called state.
We say this dot state equals whatever you want to store.
Now, in the new way of react with functional components, we have to use what are called hooks, H-O-O-K.
Okay, it's a little weird at first, but that's just the way it builds.
Let's do it.
How do we tell react to keep track of these posts?
Well, we got to take this array here, and we're going to pass it to use state function.
Let me make this bigger, close this.
So pass the array to use state.
Now, use state is going to be undefined.
You can either say react on use state or go up there.
Some people like doing this.
So this way works.
The other way is some people like destructuring here with use state.
You're going to see that a lot, because they're lazy to react dot.
Okay, and then this thing.
Now, what does it return?
Well, use state will take an initial value for this thing you want to track.
Now, it returns an array.
Okay, now this array has two things.
The first element is the variable through which you access the value.
And the second one is a function to mutate or change the value.
So if you want to use it this way, you would have to do this.
If you want to access it post sub zero.
If you want to change it post sub one and pass like a function, the new value like copy out a post and add a new object ID for like this.
But this people don't like doing this.
So what they do is they extract the first element of your array and the second element into two separate variables.
Now to do that, you just have to destructure with the square brackets like this.
Set posts and they usually always follow this convention of posts, whatever you want variable name and then set whatever that variable name is.
This way have access to posts and the function to change it.
Okay, now going back here, when I wanted to add a new post, instead of saying post that push, I just say, like, call this function set posts with this new value.
But there's a catch here.
If I do it like this, what do you think is going to happen, but those already know some stuff.
It's not going to be good.
Let's see what happens.
Boom.
Okay, so this replaces the whole array.
So the first fix would be, okay, make this an array.
Right.
That's the first fix, but it's still going to be bad because you lose all the other posts.
So that's the catch with the new way of doing react, which is functional.
The state does not merge with the previous value.
When we did before with class, and we call this that's that state would merge without now it doesn't.
So you always have to take care of copying the existing state value and then adding on the new thing.
And to do that, because it's an array, you can copy the elements by saying dot dot dot, the variable that accesses the arrays, which is posts.
And this way, when I set the posts, it's going to create a new array with this new object at the top, followed by all the existing ones.
So I'm not going to refresh.
So you can see one, two, three.
And if I click create posts, whatever is now at the top.
Okay, you can see there, all of them.
When we say set posts, we're telling react, react, I have changed.
I want to change the value for posts.
And when react sees that the value for posts is changed, it will react.
Hey, we're reacting to a change right now.
The state is changed.
Therefore, we must take care to re-render the component.
When it re-renders, basically it calls the function app again, returns this thing.
But now when it comes to the post, it's going to be the post with the new value, right?
With the new object at the top.
Therefore, it's going to also return the first one with whatever.
That's why it appeared.
And this thing will reflect in the actual DOM.
React is behind the scenes, making sure that the DOM always reflects.
What we envision here.
You might hear this a lot about virtual DOM because react has its virtual DOM.
That is comparing of the actual DOM, the actual document that people are seeing.
And whenever there's a discrepancy, react is going to work to make whatever its virtual DOM is looking like.
Make the actual document look like that.
Okay, so this basically what happens whenever there's a state change, the component re-renders.
Remember that.
That's the key element.
All right, so nice.
But now we want to see what if I want to access what the user typed, not just say whatever.
I want to put something here, click create post, and that text should appear there.
Now to do that, we have to control this input here.
It's called controlling a component.
So the input, it has a value.
Now that value has to be known to react.
So what we're going to do is create a new state variable for the value.
Let's call it title.
And then we're going to go up here and use state again.
Yes, again, you can have a separate state.
Use state.
Now I want to keep track of what the user typed for the title.
That's initially going to be empty.
So I'm going to put empty string.
And remember, we got a destructure with let's call this new title and then set new title.
Destructure the two elements in the array.
And then I can finally use new title as the value for this thing here.
Actually, I call it title.
I should call it that way.
Sorry, set title instead of new.
And there you go.
Now if I type, nothing happens.
Why?
Because title is always set to empty string constant.
The only way you can change it is through set title.
Now how do we do that?
Well, go to the input, add a known change.
Like this.
And this event, okay, we got a passive function that will receive the event object.
And through the event object, we can access the value of the element.
Now some people like defining this inline, meaning I can put the function here like this.
And I would set the title to something.
I can do that.
See something.
If I type something appears, but that's not what I want.
I want what the user typed.
So I can access event.target that gives me the actual input element and it has a dot value.
Oops, not to us.
Now if I type something there, as it changes every time I type a letter, it's actually calling set title.
Okay.
Now it works.
Now this way allows us to access the title value whenever we do the set post in on submit.
So instead of whatever here, I can just say title, which comes from this.
So let's try again when I type.
Hello there.
Click create post.
It appears here.
Okay.
Now this is called controlled component.
And we are always at a value and a known change.
Somebody asked, can we get an input value from events?
Is this what I just showed you, right?
What the user typed event here gives you information about what just happened.
It was a known change event.
Who triggered it?
Target is this element here, an input.
This element input has a property value.
When the form is submitted instead of state variable.
Can we get an input value?
Okay.
Are you trying to do the, okay.
You got to keep in mind the react way is different from the HTML CSS JavaScript traditional way.
Okay.
And if you're asking about on submit, if I would manually document, get element by ID, the title input, and then I would get the value and I'll put it here.
Is that what you're asking?
You can do this, but this is not the recommended way and people should not be doing that way because you're kind of bypassing react.
Only do that if you're hacking something for some reason cannot get it to work through the react state.
Because you want to get it in the react space so that react knows about it.
And whenever it changes it, anything else on the page will react to it if necessary.
That's why it's important to do that.
Otherwise it would never know what's going on.
But it's sad, similar as you get an input value in on change.
Do the same.
Into the same in on submit.
Not sure what you're saying.
We can discuss more discord if you want.
But if you're asking about if you want to change submit the form when you change the input here, like here.
Sad post.
You can do that if you want.
But that's not the, in this case, because I have a form, I should delegate everything to the form as a submit event.
That's the best practice, right?
But if you have something in isolation without a form, you can certainly use that.
That's fine.
All right.
Anyway, if you want to discuss more, let's go discord.
All right.
So that's good for everybody.
Let me show you how can get data from the server.
I know it's going to be too fast because we're at the end, but basically, if I want to move all this data to the, it would be in the server.
So we got to make an HTTP request to get it.
Now I have this nice website here where I can click post, and it will give me some fake data.
So this is the link I want to send you.
And it will give you some fake data.
So if you use that link, it will give you like, I use the limit here to put three, because there's too many.
You get this nice JSON formatted array.
We can leverage that.
So, okay.
So how do we do HTTP request?
Well, you can use the FATCH API.
But where do we do that in React world?
So when you fetch data, that's called a side effect.
So React wants you to use a hook for side effects called use effect.
Okay.
So the way it works is like this.
Let me show you here.
We're going to call use effect.
React, I use effect.
If you want to destructure the top, feel free to do so.
And this, you got to pass a function.
Okay.
A callback function.
Let's be past a function like this where people will like confused about error function.
Now what's happening here is the following.
React will call this function that's provided after each render of this component.
Okay.
After every render, call the use effect function.
Okay.
But we don't want to be getting the data all the time for this situation right now.
We just get it once when we mount the component.
Now, the second argument to use effect is an array of dependencies.
That usually you would pass some variables that if they change, this function would be
called upon that change.
After the first render.
After the render.
Any render.
Now, if you put empty array here, what it does is tells React, hey, I want this function
to be called only after the very first render.
But after that, don't call it anymore.
So only call it once.
So I'm going to get the data only once after mount.
So what we want to do here, let's move this thing.
I want to make an empty array there for the post.
So we have nothing.
So I want to simulate set timeout here.
So you can see it's actually going to change after two seconds.
So I'm going to call set posts with those posts like this.
And after two seconds, it should set.
See that?
Because the use effects was called after the initial render, and then I put the set timeout
to call this after two seconds.
And then if I render again by typing anything, it's still set timeout.
Okay, but this has to come from the server, not from this thing.
So let's remove the timeout as just an example to delay.
So this set post will be something from the server that I'll call posts.
And I don't yet have it.
Let me put it on the side here.
So I'm going to call fetch with that address that I pasted the zoom chat.
This will make a get HTTP request to this URL.
And this returns a promise.
Okay, so when you have a promise, it means something that a promise to give back later.
Basically, it takes time to make the request of the server from the server to respond with something.
If you want to handle the promise, you always got to do after the fetch call,
got to chain it with dot then dot then pass some function.
Okay, so what's happening is when the promise is fulfilled,
that is you got the data from the server, it will call this function that is provided to the then here.
So this function will receive as an argument a response.
That's an object that represents the response obtained from the server.
Now this response has a body with the data.
Now that body, we know it's in JSON format.
But if there is an error, you would have to handle that.
So I'm not going to do errors.
So I leave as an exercise.
If there's an error is probably going to be status around outside of the two xx range,
which a response that okay will be not okay.
You can handle that.
If it's okay, we assume got the response fine.
We can extract from the body the response of the response.
We can say response dot JSON like this.
So I take the body extracted in JSON format, basically an array of objects.
But this also returns a promise.
So you got to do the then again.
So what you got to do after this then you got to do a dot then again to handle this promise that was returned here.
And that will in turn return the body extracted, which is just the posts array of posts.
And then finally, we can call to set the posts inside.
I move the thing inside there.
Okay.
And you can see now it's getting that automatically right away, right?
If I refresh, it's very fast.
But what's actually doing is calling fetch waiting for the response and then changes from empty to all these three.
Okay, so that's use effect.
If you need anything on your document like to change, depending on the value of some other thing changing, you can use effect.
And then you pass the array of dependencies here.
And then things would change according that is this function will be called when whatever you pass as the dependency here would be changed.
Okay, typically we use these days people like to use libraries to handle data fetching.
If you're a react client side, you can use 10 stack query, which used to be called react query.
I can use SWR, which comes from next JS, which is react on the server side.
If you're interested in server side render react, look into next JS.
Okay.
And yeah, I think that's it basically as an exercise if you want to go further to try to submit here you would actually have to call on the server make effect request, but you got to pass a post, not instead of get, which would pass an argument.
Second argument to fetch is an object.
And you can use basically you can do that I think this fake API handles a new post like this method is post body is whatever you type like a JSON string of five title like this, and you would take this like that.
And maybe you want to add some headers, content type location, JSON, and like that.
So this would make the post request and then you do that then I probably returned a new post with the ID, created post, and you can use that to set this ID here.
I did it already fast because I wanted to exercise later, but I'm not explaining what's going on much basically this and it created posts.
I usually here would be usually when you create a resource it gives you back the whole resource object so you're safe to just put it here.
Like that.
And let's see what's going on.
Message is read only something going on about a message here.
Know that is that I made a mistake in the.
Let me debug.
Like this.
Something is wrong here so I'm debugging your comments.
If I call patch like that will work.
It still works.
Okay.
The method headers.
Will it still work.
Let's see and put the dot then outside.
Now do it like this.
This is debugging exercise.
Okay, that's working.
Dove tools network tab and I'm making the request.
Let's see if I type anything.
It's making a request.
Yes, it's giving the ID here.
There you go.
So that's working and I say.
What did I do here.
Some things were all that you don't have this year right.
There.
And this is complaining.
I created post.
Okay.
This is the problem.
What if I set posted empty.
That'll be empty.
Yes.
What I copy the existing posts.
Still the same.
Okay, this created post is complaining about that.
Oh, because they have a comma.
That's the problem right.
Comma.
Silly mistake.
Syntax.
Anyway, let's see.
And then it would give back in the response.
Let's try again.
Let's see.
And let's monitor XHR.
This one here.
Response.
Let's see is here ID there.
We got an object.
So we take that put it here.
Oh, is it missing the body?
What is the object not valid?
Obviously it doesn't have a body.
So body read empty.
There's still some problem.
What is the problem?
Anybody know?
Let's go here.
Post ID.
Body.
You got that.
You got the other.
Let's go to that tools.
Console.
ABC.
Objects not valid.
React on object readable stream collection.
It seems like let me debug this.
Let me see if I can show you the bug.
I don't know if it's going to work in this environment.
Let's see.
Let's do two.
Where did you do that?
Right.
This is the debugger in the DevTools.
If you pull open DevTools in Chrome is going to be under sources.
But this one is Firefox.
So that's why it's called debugger.
So if you pull open DevTools in Chrome is sources,
then press control P,
find the file,
that's a JS,
and press,
and you can put some break points here.
For example, right here,
I want to see what's going on when I do this part here.
Because I don't know what the,
what the hell is going on here, right?
Sorry about that.
So I put a break point here,
and I would basically,
trigger it by
submitting something.
ABC create,
and it would trigger here.
So I'm stopped.
I can click here and see what happened.
It's the response.
That's the problem.
It's not the actual object.
Why?
Why?
As I told you,
the problem here
is fetch returns a response.
And we first got it,
after getting the response,
you got extract from the body.
So this might be a very common mistake to do
if you're starting out the fetch.
You don't know that it returns a response
instead of the body right away.
So to fix that,
here I'd have a dot then,
that's a function
to extract the body from the response
with response JSON like that.
And obviously I didn't take care of errors.
You would have to do it here.
Try again.
ABC, let me open DevTools.
Now we're going to confirm
when you press click post,
do I get an object now?
We do.
Right?
That's working.
And I think the code didn't change here.
I think I have to refresh or something.
The DevTools weird.
But it's actually there.
Try again.
I refreshed it.
So you should see the response here.
So when I click create post,
it stops here.
You can highlight this, create post,
and it shows the actual body.
And that's working so I can remove the breakpoints.
I think that's it.
I think on the side I can remove
somewhere here.
My screen is very small.
I don't know where it is.
Let me see.
This somewhere here.
Anyway,
there you go, ABC,
the CDF,
and it's working now.
Okay, so I forgot this part.
Okay, and with that, I finished the lecture.