First assignment with React

In the last few days I’ve been learning how to use react and finally got through some of the basics. After going through some of the basics I had to do a small assignment….

In the last few days I’ve been learning how to use react and finally got through some of the basics. After going through some of the basics I had to do a small assignment.

The instructions were:

  • Create TWO new components: UserInput and UserOutput
  • UserInput should hold an input element, UserOutput two paragraphs
  • Output multiple UserOutput components in the App component (any paragraph texts of your choice)
  • Pass a username (of your choice) to UserOutput via props and display it there
  • Add state to the App component (=> the username) and pass the username to the UserOutput component
  • Add a method to manipulate the state (=> an event-handler method)
  • Pass the event-handler method reference to the UserInput component and bind it to the input-change event
  • Ensure that the new input entered by the user overwrites the old username passed to UserOutput
  • Add two-way-binding to your input (in UserInput) to also display the starting username
  • Add styling of your choice to your components/ elements in the components – both with inline styles and stylesheets

I had a bit of problem passing properties to the components and adding styles with inline css styles. Since I’m still a bit new to React I had to keep going back to old code to remind myself how to do certain things. I did manage to fulfill all the instructions for the assignment

React assignment.

Intro to data association

During the weekend I made to the section data association in the tutorials. This part of the section explain what data association is and how we use it. Data association allows us to have…

During the weekend I made to the section data association in the tutorials. This part of the section explain what data association is and how we use it. Data association allows us to have multiple collections in our database that are related to one another. There are three different types of data associations; one to one, one to many, and many to many. There are two ways to write these association, by using embedding data and referencing data.

Embedding Data

For embedding data we made two different mongoose schemas, one for users and the other one for posts. In the Post schema we just added the title and the content the user would write. For the User schema we used email, name, and then we create an array where the posts the user writes would be inserted. We used the push method to embed the post created into the user collection. Now the post collection would hold all post created by all users. But the user collection would hold all users and within in each user object it would hold only the posts created by the one user.

var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/blog_demo', {useMongoClient: true});

//POST - title, content

var postSchema = new mongoose.Schema({
   title: String,
   content: String
});

var Post = mongoose.model("Post", postSchema);

//USER - email, name
var userSchema = new mongoose.Schema({
   email: String,
   name: String,
   posts:[postSchema]
});

var User = mongoose.model("User", userSchema);

// var newUser= new User({
//    email: "hermione@hogwarts.edu",
//    name: "Hermione Granger"
// });

// newUser.posts.push({
//    title: "How to brew polyjuice potion",
//    content: "Just kidding. Go to potions class to learn it!"
// });

// newUser.save(function(err, user){
//     if(err){
//          console.log(err);
//     }else{
//          console.log(user);
//     }
// });

// var newPost = new Post({
//     title: "This is a new post.",
//     content:"This is a new post for associations."
// });

// newPost.save(function(err, post){
//    if(err){
//        console.log(err);
//    } else{
//        console.log(post);
//    }
// });

User.findOne({ name: "Hermione Granger"}, function(err, user){
   if(err){
      console.log(err);
   }else{
      user.posts.push({
         title: "3 Thing I really hate",
         content: "Voldemort, Voldemort, Voldemort"
      });
      user.save(function(err, user){
         if(err){
            console.log(err);
         }else{
            console.log(user);
         }
      });
   }
});

Referencing Data

The second way we can create data association is through referencing data. In embedding data we push the whole post into the array but when referencing data we just keep just the ids of the post instead of the whole thing. I first created a new user in the database. When I had to create the post I had to find the user and then push the data from the post into the user object. once the post was created the id of the post would be referenced inside an th array in the user object. Then by using mongoose populate I was able to find the user by id and then targeting the post. When this happens the function runs after where if there isn’t an error it’ll write out the user object with the entire post they have created. But in the database when you search for the user and look in posts only the ids of the posts will come up.

database:

Running the code:

var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost/blog_demo_2', {useMongoClient: true});

var Post = require("./models/post");
var User = require("./models/user");

// User.create({
//   email: "bob@gmail.com",
//   name: "Bob Belcher"
// });

// Post.create({
//   title: "How to cook the best burger pt.4",
//   content:"hfsbfksirfnilrf"
// }, function(err, post){
//     User.findOne({_id : "5a4f026397422c13d19164f6"}, function(err, foundUser){
//         if(err){
//             console.log(err);
//         }else{
//             foundUser.posts.push(post);
//             foundUser.save(function(err, data){
//                 if(err){
//                     console.log(err);   
//                 }else{
//                     console.log(data);
//                 }
//             });
//         }
//     });
// });

User.findOne({_id : "5a4f026397422c13d19164f6"}).populate("posts").exec(function(err, user){
    if(err){
        console.log(err);
    }else{
        console.log(user);
    }
});

 

Final Project: Weather App

As our final project we had to remake the weather from last semester but instead of using php we had to use Node.js. This was a bit difficult since I’m still getting used to…

As our final project we had to remake the weather from last semester but instead of using php we had to use Node.js. This was a bit difficult since I’m still getting used to node but I finally got it to work.

Check it: Weatherapp

I did run into a few problems the first one being the most silliest of mistakes. My first mistake was thinking the my API keys were inactive but really I had it set up wrong. The example on the Open Weather was this, “http://api.openweathermap.org/data/2.5/forecast?id=524901&APPID={APIKEY}”. You are supposed to take the curly braces out and just put your API key but what I did was leave the braces with my API key. This kept giving me an error of invalid API key.

Once I finally resolved the API key issue I went to look at some past tutorials to review how to use the body-parser package. Body-parser made it easy for me to be able to gather the information that I needed since it can turn the JSON information you get into an object. The problem I ran in was turning to figure out what was the request I needed to make so I can get th information into my ejs file. I ended up using both a GET request and a POST request. The GET request would just rendered the ejs file to get to the Index page. Here the user is able to put the city they want the weather from. Once the user inputs the city and clicks submit the POST request would run. The POST request grabs the input the user made and adds it to the search request its sending to OpenWeather. Once the information gets back it is displayed on the page for the user to see.

GET Request.

POST request.

Another issue ran into was handling an error. When the user typed in an invalid city it just sent them to an error page. What wanted to do was keep them in the Index route but just have the error code come up with the error message. I also add another part to the message telling the user to try again. This part took the longest because I had to make sure I was declaring the right variables in the ejs file so that no undefined error came up. I also had to right the if statements in the correct order for this to work as well.

Perus = Typo

Error message the user gets.

The next thing I work on was getting the the div that held the weather or error information come up only once the the submit button was clicked. I need this by making an if statement where if the data was empty it would display none and once the data had information about the weather or error it would display. This project was a great way to practice what I’ve been learning this semester about node.js and I really enjoyed it.

My Weather App Code:

var express    = require("express"),
    app        = express(),
    bodyParser = require("body-parser"),
    request    = require("request");

var data = undefined;    
var err  = undefined;
var code = undefined;

app.use(express.static('public'));    
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");

app.get("/", function(req, res){
    res.render("index", {data: data, err: err, code: code});
    
});

app.post("/", function(req, res){
    
    var cityName = req.body.city;
    
    request('http://api.openweathermap.org/data/2.5/weather?q=' + cityName +'&APPID={APIKEY}', 
        function(error, response, body){
        if(!error && response.statusCode == 200){
            var data = JSON.parse(body),
                fah  = Math.floor(Number(data["main"]["temp"]) * 9/5 - 459.67);
                
            res.render("index", {data: data, cityName: cityName, fah: fah, err: err, code: code}, 
             function(err, html){
                if(!err){
                    res.send(html);
                }else{
                    
                    console.log(err);
                    res.send(response);
                    
                }
                
            });
        }else {
            
            data = JSON.parse(body);
            
            var err  = error,
                code = data["cod"],
                mess = data["message"];
                
            res.render("index", {data: data, err: err, mess: mess, code: code}, 
                function(err, html){
                if(!err){
                    res.send(html);
                }else{
                    console.log(err);
                    res.send(response);
                    
                }
            });
            
             console.log(err);
             
        }
    });
    
});

app.listen(process.env.PORT, process.env.IP, function(){
    
   console.log("Server Started"); 
    
});

<% include partials/header %>

<div class="container">
    
    <h1>What's the Weather?</h1>
         
    <div id="weatherbox">
        <% if(data === undefined){ %>
                <p="info"></p>
        <% } %>
        <% if (err !== undefined && code !== undefined){%>
            <h1><%= "ERROR " +  code %> </h1>
            <p id="info"><%= mess + " please try again or try a different city." %></p>
        <% } %>
        <% if(data !== undefined && err === undefined){  %>
            <p id="info"><%="The weather in " +cityName+ " is currently " +
            data["weather"][0]["description"]+". The temperature is " +fah+ "˚F with a wind speed
            of " +data["wind"]["speed"]+ " MPH." %></p>
        <% } %>
        
    </div>
    <form action="/" method="POST">
        <div class="form-group">
            <label for="city">Enter the name of a city.</label>
            <input type="text" class="form-control" id="city" name="city" aria-describedby="city" 
            placeholder="E.g. New York, Tokyo" value="">
        </div>
        <button id="myBtn" type="submit" class="btn btn-primary">Submit</button>
    </form>
         

         
</div> 

<% include partials/footer %>

<!DOCTYPE html>
<html>
 
    <header>
        <title> Weather </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/
        bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/
        AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
        <link rel="stylesheet" type="text/css" href="css/style.css">
    </header>
    
    <body>

<!-- Functions js-->
    <script type="text/javascript" src="js/functions.js"></script>
    
    <!-- jQuery first, then Tether, then Bootstrap JS. -->
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" 
    integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" 
    crossorigin="anonymous"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" 
    integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" 
    crossorigin="anonymous"></script>
    
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" 
    integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
    crossorigin="anonymous"></script>
  </body>
 
</html>

html { 
    background: url(https://farm2.staticflickr.com/1113/654057570_c13af4cb91.jpg) 
    no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}
      
body {
          
    background: none;
          
}
      
@media (min-width: 768px) {
            
    .container{
                
        max-width: 576px;
                
    }
          
}

@media (min-width: 992px) {
            
    .container{
                
        max-width: 576px;
                
    }
          
}

@media (min-width: 1200px) {
            
    .container{
                
        max-width: 576px;
                
    }
          
}
      
.container {
          
    text-align: center;
    margin-top: 100px;
          
}
      
input {
          
    margin: 20px 0;
}
      
#weatherbox{
    
    margin: 20px auto;
    padding:15px;
    background-color: rgba(135, 206, 250, 0.5);
    display: none;
}
#info{
    font-weight: bold;
    font-size: 16px;
}

var data = document.getElementById("info");

if( data !== null){
    var x = document.getElementById("weatherbox");
    x.style.display = "block";
}

 

YelpCamp V1

I finally started working on the YelpCamp part of the tutorials. This is the first time I’m creating a working app with a database so I’m very excited to see what new things I’ll…

I finally started working on the YelpCamp part of the tutorials. This is the first time I’m creating a working app with a database so I’m very excited to see what new things I’ll from this. In this app the user will be able to search campgrounds that are listed here and create any new entry for another campground they would like to list. I managed to finish version 1 of the app. This is how the work looked. For this version we haven’t connected to any database just yet but I will be using mongoDB.

This is the javascript page where I’ll be setting up the routes for the app.

var express = require("express");
var app = express();
var bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");

var campgrounds = [
     
   {name: "Salmon Creek", image: "https://farm4.staticflickr.com/3872/14435096036_39db8f04bc.jpg"},
   {name: "Granite Hill", image: "https://farm8.staticflickr.com/7268/7121859753_e7f787dc42.jpg"}, 
   {name: "Mountain Goat's Rest", image: "https://farm9.staticflickr.com/8577/16263386718_c019b13f77.jpg"} 
     
];

app.get("/", function(req, res){
    
   res.render("landing");
    
});

app.get("/campgrounds", function(req, res){
        
   res.render("campgrounds", {campgrounds: campgrounds});
    
});

app.post("/campgrounds", function(req, res){

   //get data from form and add to campgrounds array
   
   var name = req.body.name;
   var image = req.body.image;
   var newCampgrounds = { name: name, image: image };
   
   campgrounds.push(newCampgrounds);
   //redirect back to campgrounds page
   
   res.redirect("/campgrounds");
   
});

app.get("/campgrounds/new", function(req, res){
   
   res.render("new");
   
});

app.listen(process.env.PORT, process.env.IP, function(){
    
   console.log("Server Started"); 
    
});

The first version of our landing page.

<% include partials/header %>

<h1> This is the landing page. </h1>

<p> Welcome to YelpCamp!</p>

<a href = "campgrounds"> View all Campgrounds </a>

<% include partials/footer %>

This page is where all the campgrounds will be shown. At this point we have added bootstrap but I have only done some internal styling but this wil be moved to an external styling sheet.

<% include partials/header %>

<div class="container">
    <header class="jumbotron">
        
        <h1> Welcome to YelpCamp </h1>
        <p> View our hand-picked campgrounds from all over the world </p>
        <p> <a class="btn btn-primary btn-large" href="/campgrounds/new"> Add New Campground </a> </p>
    
    </header>
    
    <div class="row">
        <div class="col-lg-12">
            <h3> Our Most Popular Campgrounds! </h3>
        </div>
    </div>
    
    <div class="row text-center" style="display: flex; flexwrap: wrap;">
        <% campgrounds.forEach(function(campgrounds){ %>
        
            <div class="col-md-3 col-sm-6">
                
                <div class="thumbnail">
                    
                    <img src = "<%= campgrounds.image %>">
                    <div class="caption"> <h4> <%= campgrounds.name %> </h4> </div>
                    
                </div>
                
            </div>
            
        <% }) %>
    </div>
    
</div>

<% include partials/footer %>

This page will hold the form where a user can list a new campground to the database.

<% include partials/header %>
    
<div class="container">    
    <div class="row">
        <h1 style="text-align: center;"> Create a new Campground </h1>
           
        <div style="width:30%; margin: 30px auto;">
            <form action="/campgrounds" method="POST">
                
                <div class="form-group">
                <input class="form-control" type="text" name="name" placeholder="name">
                </div>
                <div class="form-group">
                <input class="form-control" type="text" name="image" placeholder="image url">
                </div>
                <div class="form-group">
                <button class="btn btn-lg btn-primary btn-block"> Submit! </button>
                </div>
                
            </form>
            <a href="/campgrounds"> Go Back </a>
        </div>
    </div>
</div>

<% include partials/footer %>

I also made 2 partials for the header and footer that will be include in other ejs files.

<!DOCTYPE html>
<html>

    <header>
        <title> YelpCamp </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    </header>
    
    <body>
        
        <nav class="navbar navbar-default">
            <div class="container-fluid">
                <div class="navbar-header">
                    <a class="navbar-brand" href="/"> YelpCamp </a>
                </div>
                <div class="collapse navbar-collapse">
                    <ul class="nav navbar-nav navbar-right">
                        <li> <a href="/"> Login </a> </li>
                        <li> <a href="/"> Sign Up </a> </li>
                        <li> <a href="/"> Log Out </a> </li>
                    </ul>
                </div>
            </div>
        </nav>

</body>
 
</html>