These are chat archives for FreeCodeCamp/Help

1st
Jul 2018
Christopher McCormack
@cmccormack
Jul 01 2018 00:20
@brimarq Remove the whitespace after Heading 1 and Heading 2, you should be good.
Brian Marquis
@brimarq
Jul 01 2018 00:24
@cmccormack Thx... that worked! Weird. I've always been in the habit of using two spaces before a CR when writing MD text. I guess the regex in the tests don't like that.
Christopher McCormack
@cmccormack
Jul 01 2018 00:24
@brimarq yeah that was a weird one, I did just about every other test until I realized what was going on :D
Brian Marquis
@brimarq
Jul 01 2018 00:29
@cmccormack Yep… I even saw something about whitespace creating problems on another post but didn’t think about it being in the #editor because of my old habit. I kept looking for it in the #preview, trying to figure out what marked was doing with the conversion. Good grief. LOL
Christopher McCormack
@cmccormack
Jul 01 2018 00:48
@brimarq haha may be a good issue to submit, request they make that test a little less strict maybe
anthonygallina1
@anthonygallina1
Jul 01 2018 01:02
:wave:
Kyle Holm
@thekholm80
Jul 01 2018 01:05
@anthonygallina1 :wave:
anthonygallina1
@anthonygallina1
Jul 01 2018 01:36
:hourglass_flowing_sand:
glitz20
@glitz20
Jul 01 2018 03:00
anybody familiar with react and express?
sendData(data) {
    axios.post('http://localhost:4200/items/add/post', {
        itemname: data,
        category: data
    })
    .then(res => this.setState({ items: res.data }))
    .catch(err => console.log(err))
  }
is this the right way to post data in react using axios?
Kyle Holm
@thekholm80
Jul 01 2018 03:11
looks good to me
Ryan Williams
@Ryanwfile
Jul 01 2018 03:12

For the responsive projects -> survey, one of the tasks is Inside the form element, I am required to enter my name in a field with id="name"
I have tried a lot of variations of

 <form id = "survey-form">
     <label id="name-label" for= "name">Name: <input id="name" type ="text" placeholder ="name"></input></label>
</form>

and none of them pass the id="name" test, I've also tried to put id on a div container for this input field and that also doesn't work, what am I doing incorrectly? Thank you very much for any help.

Kyle Holm
@thekholm80
Jul 01 2018 03:13
have you tried removing the input field from the label?
since you're using the for parameter, you don't have to nest the input in the label
<form>
  <label ...>Name: </label>
  <input ... />
</form>
Ryan Williams
@Ryanwfile
Jul 01 2018 03:18
@thekholm80 I will try that, thank you
glitz20
@glitz20
Jul 01 2018 03:19
@thekholm80 I don't know why,but I cannot see the data in database (mlab)
<label>
              Add Item:
              <input name='itemname' type="text" onChange={this.handleChange} className="form-control"/>
                  </label><br />
                  <label>
                      Category:
              <input name='category' type="text" onChange={this.handleChange} className="form-control" />
                  </label><br />

            <input type="submit" value="Submit" className="btn btn-primary"/>
this is my form in react
Kyle Holm
@thekholm80
Jul 01 2018 03:19
@sabin20 what is firing your sendData() function?
Ryan Williams
@Ryanwfile
Jul 01 2018 03:19
@thekholm80 just tried it, still doesn't work
Kyle Holm
@thekholm80
Jul 01 2018 03:21
@Ryanwfile is your project in codepen? it's easier to debug if i can see it
Ryan Williams
@Ryanwfile
Jul 01 2018 03:21
glitz20
@glitz20
Jul 01 2018 03:22
@thekholm80 I am sorry, but I quite donot know what you mean by that
Kyle Holm
@thekholm80
Jul 01 2018 03:22
@sabin20 how is sendData() being called?
@Ryanwfile weird, codepen is timing out
image.png
Ryan Williams
@Ryanwfile
Jul 01 2018 03:24
@thekholm80 yea there's been some weird glitches with this script, some tests pass and fail randomly
Kyle Holm
@thekholm80
Jul 01 2018 03:24
i wonder if some of your problem is codepen?
glitz20
@glitz20
Jul 01 2018 03:25
@thekholm80 I have tried to clone this project and make modification.This might give you idea about my code.
https://appdividend.com/2017/06/28/mern-stack-tutorial/
glitz20
@glitz20
Jul 01 2018 03:25
I am trying to add one more field to item called category
Kyle Holm
@thekholm80
Jul 01 2018 03:25
they have <form onSubmit={this.handleSubmit}>
does yours say <form onSubmit={this.handleSubmit}>? because you named your function sendData() not handleSubmit
it's really hard to see a few lines of code and get a good idea of what's going on
Ryan Williams
@Ryanwfile
Jul 01 2018 03:27
@thekholm80 looks like codepen is down
Kyle Holm
@thekholm80
Jul 01 2018 03:27
yeah, i'm getting a 502 response now
glitz20
@glitz20
Jul 01 2018 03:28
render() {
      return (
        <div className="container">
              <form onSubmit={this.handleSubmit}>

            <label>
              Add Item:
              <input name='itemname' type="text" onChange={this.handleChange} className="form-control"/>
                  </label><br />
                  <label>
                      Category:
              <input name='category' type="text" onChange={this.handleChange} className="form-control" />
                  </label><br />

            <input type="submit" value="Submit" className="btn btn-primary"/>
          </form>
      </div>
      );
    }
  }
Kyle Holm
@thekholm80
Jul 01 2018 03:28
@sabin20 what does your handleSubmit function look like?
glitz20
@glitz20
Jul 01 2018 03:29
 handleSubmit(event) {
      event.preventDefault();
      this.addItemService.sendData(this.state.value);
      this.props.history.push('/');
    }
Kyle Holm
@thekholm80
Jul 01 2018 03:29
ah, okay
and what does your addItemService object (or class?) look like?
glitz20
@glitz20
Jul 01 2018 03:31
class ItemService {

  sendData(data) {
    axios.post('http://localhost:4200/items/add/post', {
        itemname: data,
        category: data
    })
    .then(res => this.setState({ items: res.data }))
    .catch(err => console.log(err))
  }

  updateData(data, id){
    axios.post('http://localhost:4200/items/update/'+id, {
      item: data
    })
    .then(res => this.setState({ items: res.data }))
    .catch(err => console.log(err))
  }

  deleteData(id){
    axios.get('http://localhost:4200/items/delete/'+id)
    .then().catch(err => console.log(err))
  }
}

export default ItemService;
and this is additem class
class AddItem extends Component {

  constructor(props) {
      super(props);
      this.state = {
          itemname: '',
          category: ''
      };
      this.addItemService = new ItemService();

      this.handleItemChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({ [event.target.name]: event.target.value });
    }


    handleSubmit(event) {
      event.preventDefault();
      this.addItemService.sendData(this.state.value);
      this.props.history.push('/');
    }

    render() {
      return (
        <div className="container">
              <form onSubmit={this.handleSubmit}>

            <label>
              Add Item:
              <input name='itemname' type="text" onChange={this.handleChange} className="form-control"/>
                  </label><br />
                  <label>
                      Category:
              <input name='category' type="text" onChange={this.handleChange} className="form-control" />
                  </label><br />

            <input type="submit" value="Submit" className="btn btn-primary"/>
          </form>
      </div>
      );
    }
  }
Kyle Holm
@thekholm80
Jul 01 2018 03:33
when you submit do you get any errors in your console?
browser or terminal
glitz20
@glitz20
Jul 01 2018 03:34
No I donot get any error
Lance
@texas2010
Jul 01 2018 03:34
why ~~~? it suppose to be ```...
glitz20
@glitz20
Jul 01 2018 03:34
When I submit the form, there is no any error, but the item is not added to database
Kyle Holm
@thekholm80
Jul 01 2018 03:35
@sabin20 can you try changing your ItemService to add:
  sendData(data) {
    axios.post('http://localhost:4200/items/add/post', {
        itemname: data,
        category: data
    })
    .then(res => {
      this.setState({ items: res.data });
      console.log(res.data);
    })
    .catch(err => console.log(err))
  }
Lance
@texas2010
Jul 01 2018 03:36
cute code
Kyle Holm
@thekholm80
Jul 01 2018 03:36
i think the problem is you're calling setState() inside a stateless class instead of your component class
so it's not really doing anything
err, maybe not. i see in that project they're doing just that
so ... dunno
@texas2010 :wave:
Lance
@texas2010
Jul 01 2018 03:38
@thekholm80 :wave:
Kyle Holm
@thekholm80
Jul 01 2018 03:40
@Ryanwfile yay it loaded - figured out why that test isn't passing
Lance
@texas2010
Jul 01 2018 03:40
when you submit the form. since you said it didnt go to database. did it go to state?
Kyle Holm
@thekholm80
Jul 01 2018 03:41
Inside the form element, I am required to enter my name in a field with id="name"
the key here is required
adding that to the element will allow the test to pass
glitz20
@glitz20
Jul 01 2018 03:42
@thekholm80 it saying unexpected token, error with parenthesis
Kyle Holm
@thekholm80
Jul 01 2018 03:42

from https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input

required HTML5
This attribute specifies that the user must fill in a value before submitting a form.

@sabin20 sorry i missed a closing }
i updated the code above
glitz20
@glitz20
Jul 01 2018 03:45
@thekholm80 there isn't any change it is same as before
Kyle Holm
@thekholm80
Jul 01 2018 03:45
what is the same?
glitz20
@glitz20
Jul 01 2018 03:45
After I submit the form, every thing is normal,
but database is not updated
Lance
@texas2010
Jul 01 2018 03:46
well.. it seems that.setState is stay in the ItemService. not going to into additem state. i think?
glitz20
@glitz20
Jul 01 2018 03:46
it only created a new i
*id
Kyle Holm
@thekholm80
Jul 01 2018 03:46
@texas2010 i think since ItemService is a class, and it gets instantiated in addItem, the class instance shares scope
@sabin20 sounds like you got a problem on the back end
glitz20
@glitz20
Jul 01 2018 03:47
Screenshot (51).png
itemRouter.route('/add/post').post(function (req, res) {
  var item = new Item(req.body);
      item.save()
    .then(item => {
    res.status(200).json({Item: 'Item added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});
this is the backend to post an item
and this is the schema.
var Item = new Schema({

      itemname: String,
      category: String


},{
    collection: 'items'
});
Kyle Holm
@thekholm80
Jul 01 2018 03:49
i don't do mongoose, sorry
glitz20
@glitz20
Jul 01 2018 03:50
but, is the express ok?
Kyle Holm
@thekholm80
Jul 01 2018 03:50
looks okay
glitz20
@glitz20
Jul 01 2018 03:52
var item = new Item(req.body);
do you think this line is fine?
Kyle Holm
@thekholm80
Jul 01 2018 03:53
assuming you've got bodyparser all set up, it should be fine
lmilliken
@lmilliken
Jul 01 2018 04:31
hi everyone, what would be the proper way to set up Mongo models and documents in Glitch? From the fcc examples, I've seen, it's through an endpoint but when I run it, nothing is added in mLabs
Ryan Williams
@Ryanwfile
Jul 01 2018 05:48
@thekholm80 Thank you so much, that explains it
Kekar
@kekar
Jul 01 2018 06:27
Hey, I started with APIs and Microservices Certification challenges yesterday. Today I am facing submitting link to my glitch project. Even for the submissions already accepted, right now running tests is giving me timeout occured error.
I do not know if the problem is with my glitch project or anywhere else?
Kekar
@kekar
Jul 01 2018 06:36
never mind. Got it.
Kranti Nebhwani
@darkphotonKN
Jul 01 2018 07:57
Is anyone able to take a look at a video for a few seconds to explain to me how this person uses .push(), because he uses it differently than I do and what i can see from MDN JS docs so I really can't figure it out
Aditya
@ezioda004
Jul 01 2018 08:01
@darkphotonKN Sure
Kranti Nebhwani
@darkphotonKN
Jul 01 2018 08:02
@ezioda004 links aren't allowed though right? Search yooutube for "Connecting Firebase to a Contact Form" its by traversy media, he writes it at 13:57
something with .push() and then .set()
A little earlier before that he makes the messagesRef variable point to Firebase server, if you need to see what he did there go a little further back
@ezioda004
Aditya
@ezioda004
Jul 01 2018 08:05
@darkphotonKN Links are allowed anyway, .push() and .set() seems like methods are coming from firebase API.
Kranti Nebhwani
@darkphotonKN
Jul 01 2018 08:05
@ezioda004 I don't understand how normally we do X.push(Y) where Y is something we push onto X array or something like that. Y becomes part of X. There's nothing in the argument here, and in MDN docs for .push i can't find anything about no argument either, so what is he pushing
Kranti Nebhwani
@darkphotonKN
Jul 01 2018 08:06
@ezioda004 ah right so it's not the standard .push
Adish Jain
@Adishjain58
Jul 01 2018 08:06

const result = {
success: ["max-length", "no-amd", "prefer-arrow-functions"],
failure: ["no-var", "var-on-top", "linebreak"],
skipped: ["id-blacklist", "no-dup-keys"]
};
function makeList(arr) {
"use strict";

// change code below this line
const resultDisplayArray =[ <li class="text-warning">${arr[0]}</li>, <li class="text-warning">${arr[1]}</li>, <li class="text-warning">${arr[2]}</li> ];
// change code above this line

return resultDisplayArray;
}
/**

  • makeList(result.failure) should return:
  • [ <li class="text-warning">no-var</li>,
  • <li class="text-warning">var-on-top</li>,
  • <li class="text-warning">linebreak</li> ]
    **/
    const resultDisplayArray = makeList(result.failure);
    console.log(resultDisplayArray);
Aditya
@ezioda004
Jul 01 2018 08:07
@darkphotonKN Check this out, and yeah its not standard array push method.
Kranti Nebhwani
@darkphotonKN
Jul 01 2018 08:07
@ezioda004 thanks a lot, was so confused lol trusting he would mention if it was using an api because of the same method name but i guess im too newbie
Henry
@GitHub-Henry
Jul 01 2018 08:41
Wondering if i should add Flow to my React apps. Any opinions about it?
Aymen
@AymenAlSalem
Jul 01 2018 08:51
Hello , can someone please visit this challenge and check if he can scroll down, "it like the page is fixed with no scrollbar". I don't know if this a bug or just my browser : https://learn.freecodecamp.org/front-end-libraries/sass/use-if-and-else-to-add-logic-to-your-styles/
Adish Jain
@Adishjain58
Jul 01 2018 08:54
@AymenAlSalem i can scroll down. i am using chrome
"use strict";
export const foo = "bar";
export const bar= "foo";
what is wrong with this code
Adish Jain
@Adishjain58
Jul 01 2018 08:59
testcase for bar is not getting passed and i don't know why
Aymen
@AymenAlSalem
Jul 01 2018 09:02
@Adishjain58 thank you so much , my bad i didn't tested it in chrome, in firefox there is no scroll bar for some reason . anyway i will switch to chrome for this challenge :)
Aditya
@ezioda004
Jul 01 2018 09:04
@Adishjain58 Add a whitespace between bar and =, nasty bug.
Adish Jain
@Adishjain58
Jul 01 2018 09:35
@ezioda004 thnx
1LifeLess
@1LifeLess
Jul 01 2018 11:05
What will be the reason for someone to assign an anonymous function to a variable?
const sum = (function() {
 })();
alpox
@alpox
Jul 01 2018 11:11
@1LifeLess That assigns the return value of the anonymous function to the variable
1LifeLess
@1LifeLess
Jul 01 2018 11:12
@alpox hmmm...ok ,thanks man
Aditya
@ezioda004
Jul 01 2018 11:15
If the returned value is a function then you can make use of closures to have private variables that only the returned function has access to. Doesnt pollute the global scope.
const sum10 = (function(){
  let a = 10;
  return function(b){
    return a + b;
  }
})();
sum10(5); //15
console.log(a); //Reference error
alpox
@alpox
Jul 01 2018 11:19
And yet I'd wonder why ever someone would need that
Its ugly :D
Like in this case, you could just create a function that is a know addition factory
const sumFactory = a => b => a + b;
const sum10 = sumFactory(10);
sum10(5); // 15
Aditya
@ezioda004
Jul 01 2018 11:28
Maybe in cases where the callback is already defined?
someNode.addEventListener("click", (function(){
  let count = 0;
  return function(e){
    console.log(e); //event object
    console.log(++count); // 1
  }
})())
Mehdi Amlal
@mehdiamlal
Jul 01 2018 11:29
Hey guys, what is the appropriate status code for "user not found"?
alpox
@alpox
Jul 01 2018 11:29
@ezioda004 I'd still not use this as its hard to see what happens. In this case I would also use a named function (factory) outside and then use the factory there
function withCounter(func) {
  let counter = 0;
  return (event) => {
    counter = func(event, counter);
  }
}

someNode.addEventListener("click", withCounter((event, counter) => {
  console.log(event);
  console.log(counter);
  return counter + 2;
}));
Aditya
@ezioda004
Jul 01 2018 11:33
@alpox I kinda like this pattern, encapsulates the variables, nothing additional added in the global scope. I'm not too familiar with functional programming patterns but I like the idea of factory functions too.
Theres also similar modular patterns, I remember seeing some in YDKJS.
Josh Queen
@josh-queen
Jul 01 2018 12:38
Hi guys, hoping to get some help with Git
I'm working on a collaborative project with two other
There are two branches with PRs waiting to be merged
Both have changed the file structure of the project
I'm assuming we'll need to commit one of them, and rework the other
But are there any rules/best practices to follow when it comes to renaming/moving files?
火柴
@huaiguoguo
Jul 01 2018 13:15
大家好
李军
@lijunqq0
Jul 01 2018 13:20

<style >
<h2 {color: blue;} </style>

<p>在大家心目中,猫是慵懒的可爱的化身,它可以睡饱了再起来吃饭,可以逗趣小耗子,可以卖得了萌,使得了坏,这样百变的小怪兽就集结在一只宠物上,怎能不惹人怜爱。</p>
h2变为蓝色?

请问怎么做
gewitterfetisch
@gewitterfetisch
Jul 01 2018 13:52
Hello everyone. I'm here for the first time as I'd like to report a not-code-related bug and the bug-reportig-howto asks everyone to look through the open github-issues first (I did) and talk about the problem in the chat.
I've encountered a problem with missing scrollbars on the instruction panel in Firefox 61.0 (64bit, Windows, 1366x769 screen resolution). In the last 15 or so "Visual Design" challenges I did lately, there's no scrollbar to see all of the conten of the instruction panel when I initially load the . To be able to scroll to the end of the content, I have to manually resize the size of the instruction panel. When I do this, the missed scrollbar appeares and everything workes peachy from there on.
image.png
Mehdi Amlal
@mehdiamlal
Jul 01 2018 14:12
Hey guys
Is it a good idea to store an access token in the database?
Or should I just store it in the browser header?
Bjorn van de Peut
@bjorno43
Jul 01 2018 14:39
@mehdiamlal Storing it in the database is fine. Probably even more secure. Just make sure that you flag your cookies as HTTP only so they can't be stolen with JS
Bjorn van de Peut
@bjorno43
Jul 01 2018 14:45
@gewitterfetisch It's perfectly fine to make a bug report on Github for that. Even if it turns out that it has been reported before or that there is no bug, it won't have any consequences for you. We rather see an accidentally "false" report of a bug than miss out on one
gewitterfetisch
@gewitterfetisch
Jul 01 2018 15:02
@bjorno43 Thank you for your feedback! I'll do that.
eber guuimaraes
@eberkaique_gitlab
Jul 01 2018 15:43
hey everyone
Bjorn van de Peut
@bjorno43
Jul 01 2018 15:44
Hello
eber guuimaraes
@eberkaique_gitlab
Jul 01 2018 15:44
image.png
I'm stumped on this can anyone help me please?
Bjorn van de Peut
@bjorno43
Jul 01 2018 15:45
Sure, that's an easy one
Mehdi Amlal
@mehdiamlal
Jul 01 2018 15:45
@bjorno43 What about storing them in a custom header?
Bjorn van de Peut
@bjorno43
Jul 01 2018 15:45
Do you remember the lesson that taught you that can add classes to elements? @eberkaique_gitlab
eber guuimaraes
@eberkaique_gitlab
Jul 01 2018 15:46
Yea
I've done everything, I've tried different things and nothing seems to work. It keeps saying the same thing :(
Bjorn van de Peut
@bjorno43
Jul 01 2018 15:46
Alright. So <div> can have a class by adding the class attribute class=''
So you get something like <div class=''>
eber guuimaraes
@eberkaique_gitlab
Jul 01 2018 15:48
I see, so then it should be <h2 class="red-text"> ?
Bjorn van de Peut
@bjorno43
Jul 01 2018 15:48
Yes, that's it :)
eber guuimaraes
@eberkaique_gitlab
Jul 01 2018 15:50
brb lemme try it. thanks.
Bjorn van de Peut
@bjorno43
Jul 01 2018 15:50
@mehdiamlal Perhaps you should explain me what it is that you're trying to do. Because it honestly doesn't make much sense to me to store an access token anywhere inside the code?
I mean, are you making a login system?
Mehdi Amlal
@mehdiamlal
Jul 01 2018 15:53
I'm currently learning token-based authentication, and I wanted to know if it's better to store a JWT token inside the user document in the database, or just in a custom browser header
I'm making a login system for a note-taking api
eber guuimaraes
@eberkaique_gitlab
Jul 01 2018 15:54
image.png
same thing :C
This ought to be the simplest hardest lesson I've come by lol
Bjorn van de Peut
@bjorno43
Jul 01 2018 16:00
@mehdiamlal Hmm I don't have any experience with JWT tokens. But I can give you a general idea of how it normally works. Normally when a user logs in, you have a session. Sessions are stored on the server and you don't have to worrie much about it yourself. The session takes care of your security. The downside to sessions is that they can only stay alive for as long as the user doesn't close the browser. As soon as the browser is closed, the session is destroyed and the user must login again on the next visit. If you want to "remember" a user, you'll have to rely on cookies. That's where the access token comes in. You store the token in the database and inside the cookie. As long as the user has that cookie and the token matches with the one in your database, you can safely create a new session for the user without the need for another login.
@eberkaique_gitlab Look at your code in there. I still see <h2>CatPhotoApp</h2>. You didn't add the class in there
Bjorn van de Peut
@bjorno43
Jul 01 2018 16:08
@mehdiamlal Just reading about JWT and they look a lot like sessions to me. With sessions you have some sort of cookie on the server with a token and a session cookie in the users browser with the same token (known as the session id). That's how the server verifies each subsequent request from the user
Dan Richards
@beingandsoul_twitter
Jul 01 2018 17:41
Hello, my submit button is not working on the website, what do?
as soon as i change a line of code, it wont let me run the tests
alpox
@alpox
Jul 01 2018 17:44
@beingandsoul_twitter We would have to see the code to really see whats up, but one problem that often comes up is that the submit button is in a form, you try to run an onsubmit javascript event and then don't see the results on the page because the page reloaded (!) - the reload is the default behavior of submitting a form. To prevent that, either use the event.preventDefault() in the onSubmit event handler (The event is passed to the event handler as an argument), or just return false at the end of your event handler
Dan Richards
@beingandsoul_twitter
Jul 01 2018 17:46
i am using this: var myStr=“I am a “double quoted” string inside “double quotes”.”;
on the Basic JavaScript: Escaping Literal Quotes in Strings challenge
i have had a similar issue on a few other challenges. Where submit will not work, even when i am 100% sure the answer is correct
what is the event handler?
Dan Richards
@beingandsoul_twitter
Jul 01 2018 17:53
it is doing it on the next challenge. I can not submit anything at all
i am using chrome
May Kittens Devour Your Soul
@diomed
Jul 01 2018 18:47
@beingandsoul_twitter do you get any errors?
u might wanna try clearing cache or using different browser, tho
Dan Richards
@beingandsoul_twitter
Jul 01 2018 18:58
no errors. it just doesnt work anymore. some challenges work, others dont
i cleared cahce and cookies. i could try firefox i guess...
Bjorn van de Peut
@bjorno43
Jul 01 2018 19:07
@beingandsoul_twitter I suggest that you share a screenshot of your code when you hit a challenge that doesn't work. Preferably with your Browser Console (F12) open. It'll help us a lot to get to the bottom of it
Mehdi Amlal
@mehdiamlal
Jul 01 2018 19:22
Hey guys! How can I keep track of requests sent to my app hosted on heroku on my terminal?
anthonygallina1
@anthonygallina1
Jul 01 2018 19:39
@mehdiamlal found some things here. Just read the list. Maybe some possibiltys? https://devcenter.heroku.com/articles/heroku-cli-commands
glitz20
@glitz20
Jul 01 2018 19:49
anyone who have used mongo and express?
itemRouter.route('/add/post').post(function (req, res) {
  var item = new Item(req.body);
      item.save()
    .then(item => {
    res.status(200).json({Item: 'Item added successfully'});
    })
    .catch(err => {
    res.status(400).send("unable to save to database");
    });
});
is this the right way to post an item?
I have two fields in Item schema named itemname and category.

So should it be just

var item = new Item(req.body);

or something like

var item = new Item(req.body.itemname,req.body.category);
Christopher McCormack
@cmccormack
Jul 01 2018 21:45
@sabin20 if req.body is an object containing the proper properties it should work fine
glitz20
@glitz20
Jul 01 2018 22:28
@cmccormack yeah I think it fine, but I cannot update my database with itemname and category
Christopher McCormack
@cmccormack
Jul 01 2018 22:29
@sabin20 are you getting an error? Is it not showing in the db or is it not returning the success json?
glitz20
@glitz20
Jul 01 2018 22:33
So here is the thing, when I submit the form
 <div className="container">
              <form onSubmit={this.handleSubmit}>

            <label>
              Add Item:
              <input name='itemname' type="text" onChange={this.handleChange} className="form-control"/>
                  </label><br />
                  <label>
                      Category:
              <input name='category' type="text" onChange={this.handleChange} className="form-control" />
                  </label><br />

            <input type="submit" value="Submit" className="btn btn-primary"/>
          </form>
      </div>
every thing is fine, there is no error
A new item and id is created but there is no itemname and category associated with that it in the database
@cmccormack
Kyle Holm
@thekholm80
Jul 01 2018 22:42
did you update your schema to accommodate the changes you made?
if your schema looks like the tutorial code, i don't think it will work
var Item = new Schema({
  item: {
    type: String
  },

},{
    collection: 'items'
});
you're passing itemname and category
glitz20
@glitz20
Jul 01 2018 22:43
so yeah I have updated that
var Item = new Schema({

      itemname: String,
      category: String


},{
    collection: 'items'
});
Kyle Holm
@thekholm80
Jul 01 2018 22:43
shouldn't it be
var Item = new Schema({
  itemname: {
    type: String
  },
  category: {
    type: String
  }
},{
    collection: 'items'
});
i don't do mongoose, but that's consistent with the tutorial code
Christopher McCormack
@cmccormack
Jul 01 2018 22:44
You can short hand it like he has it
Kyle Holm
@thekholm80
Jul 01 2018 22:44
ah
stupid mongoose
glitz20
@glitz20
Jul 01 2018 22:45
yeah both should work
Christopher McCormack
@cmccormack
Jul 01 2018 22:45
Are you logging the req.body object to ensure you have a proper object with the correct properties?
and you are using body-parser?
glitz20
@glitz20
Jul 01 2018 22:46
yeah I have
lass AddItem extends Component {

  constructor(props) {
      super(props);
      this.state = {
          itemname: '',
          category: ''
      };
      this.addItemService = new ItemService();

      this.handleItemChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({ [event.target.name]: event.target.value });
    }


    handleSubmit(event) {
      event.preventDefault();
        this.addItemService.sendData({
            itemname: this.state.itemname,
            category: this.state.category
        })
            .then(data => {
                console.log(data);
            })
      this.props.history.push('/');
    }

    render() {
      return (
        <div className="container">
              <form onSubmit={this.handleSubmit}>

            <label>
              Add Item:
              <input name='itemname' type="text" onChange={this.handleChange} className="form-control"/>
                  </label><br />
                  <label>
                      Category:
              <input name='category' type="text" onChange={this.handleChange} className="form-control" />
                  </label><br />

            <input type="submit" value="Submit" className="btn btn-primary"/>
          </form>
      </div>
      );
    }
  }
so this is my additem class
Christopher McCormack
@cmccormack
Jul 01 2018 22:46
no in your express configuration
not React
glitz20
@glitz20
Jul 01 2018 22:47
app.use(cors());
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
yeah this one is in express
does the state handling look correct?
Christopher McCormack
@cmccormack
Jul 01 2018 22:48
Right but did you actually log the req.body in your express post method to see if you're getting the correct data
glitz20
@glitz20
Jul 01 2018 22:50
yeah
itemRouter.route('/add/post').post(function (req, res) {
    var item = new Item(req.body);
    console.log(req.body)
    item.save()
smth like this,
Christopher McCormack
@cmccormack
Jul 01 2018 22:50
and it's an object?
glitz20
@glitz20
Jul 01 2018 22:50
but it is only showing empty bracket in console
~~~
Start
{}
{}
~~
Christopher McCormack
@cmccormack
Jul 01 2018 22:51
you're using some external method in React I can't validate it
you should try to avoid doing that
If you want to use a method from a parent you should pass it down as props
unless it's an external library I guess
but in that case I'm not sure why you are bothering to store it as a class property
glitz20
@glitz20
Jul 01 2018 22:53
which one?
Christopher McCormack
@cmccormack
Jul 01 2018 22:53
ItemService
glitz20
@glitz20
Jul 01 2018 22:54
class ItemService {

    sendData(data) {
        return axios.post('http://localhost:4200/items/add/post', data)
            .then(res => {
                this.setState({ items: res.data });
                console.log(res.data);
            })
            .catch(err => console.log(err));
    }

  updateData(data, id){
    axios.post('http://localhost:4200/items/update/'+id, {
      item: data
    })
    .then(res => this.setState({ items: res.data }))
    .catch(err => console.log(err))
  }

  deleteData(id){
    axios.get('http://localhost:4200/items/delete/'+id)
    .then().catch(err => console.log(err))
  }
}
my itemservice class is like this one
Christopher McCormack
@cmccormack
Jul 01 2018 22:56
start logging along the path, seems to be losing data somewhere if your req.body doesn't have your object
log your data parameter in sendData to make sure it's receiving it
glitz20
@glitz20
Jul 01 2018 23:02
sendData(data) {
        return axios.post('http://localhost:4200/items/add/post', data)
        console.log(data)
Kyle Holm
@thekholm80
Jul 01 2018 23:02
how do you reach the console.log() after returning?
glitz20
@glitz20
Jul 01 2018 23:03
sorry my bad
itemRouter.route('/add/post').post(function (req, res) {
    var item = new Item(req.body);
    console.log(req.body)
so I did log here and see no data in console