Reactjs error, objects are not valid as react child? - node.js

I'm using reactjs in front end and nodejs as backend. I'm calling my backend (localhost:3001/api/tunes) through this code :
componentDidMount(){
fetch("/api/itunes")
.then((results)=>{
this.setState({queryResult:results});
})
}
This code is supposed to return a single string value which I'm assigning to local state variable queryResult. I can't understand why the code gives error - objects are not valid react child.
My render function :
render(){
return(
<div>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search"
value={this.state.queryValue} onChange={this.handleQueryChange} />
<button class="btn btn-outline-success my-2 my-sm-0" type="submit"
onClick={this.submitQuery}></button>
</form>
<div>{this.state.queryResult}</div>
</div>
);
}
this is what I'm getting from my server:
router.get('/api/itunes',(req,res,next)=>{
request('https://itunes.apple.com/search?term=jack+johnson',
function (error, response, body) {
if (!error && response.statusCode == 200) {
// console.log(body) // Print the google web page.
var result =JSON.parse(body);
res.send(result.results[0].artistName);
}
});
});

You are trying to render whole object which is this.state.queryResult .
React cannot render objects.You must convert this to String or have to extract each value from the object.
You can easily check this using {console.log(this.state.queryResult)}

Related

Search Data not working Angular NodeJS API

i am created the search part using angular and node js. i have tested through the postman it is working fine. when connect with frond end anqular application is it not working error displayed
Failed to load resource: the server responded with a status of 404 (Not Found)
what i tried so far i attached below please check.
i tried on the url http://localhost:9001/user/findOne?first_name=kobinath
this is working well on postman but tested through the anqular didn't work. i attached the code what i tried so far.
employee.component.ts
search()
{
let name= {
"first_name" : this.first_name
};
this.http.post("http://localhost:9001/user/findOne",name).subscribe((resultData: any)=>
{
console.log(resultData);
});
}
employee.component.html
<form>
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="first_name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">
</div>
<button type="submit" class="btn btn-primary mt-4" (click)="search()" >Search</button>
</form>
</div>
What I noticed: With Postman you send first_name as a query parameter, but in your Angular-code you attach it to the request-body.
To achieve the equivalent of what you do in Postman, you could use the following code:
search(firstName: string) {
const params = new HttpParams().set('first_name', firstName);
const body = {
first_name : firstName
};
this.http.post("http://localhost:9001/user/findOne", body, { params: params })
.subscribe((resultData: any)=>
{
console.log(resultData);
});
}
Btw: Why don't you use GET instead of POST?

how to delete object array from node js

I am creating a simple todolist using react js and node js without database (to store data in objact array) I need to delete elements one by one by clicking. For each element I have Delete button. now todo list delete from front end(react), how to delete it from node any one please help me
todo.js
function Remove(id) {
const updateTodos=[...tasks].filter((obj)=>obj.id!==id)
setTasks(updateTodos)
}
if(isLogged){
return (
<div >
<h1>ToDo List</h1>
<form onSubmit={HandleSubmit}>
<input type="text" placeholder=" Add item..." name="list" value={toDos} onChange={(e)=>setToDos(e.target.value)}/>
<button id="btn" type="submit">Add</button>
</form>
<ul>
{tasks.map(obj=><li key={obj.id}>{obj.toDo}<button type='delete' onClick={(e)=>Remove(obj.id)} >Delete</button>
<input type="checkbox" id="" name=""onChange={(e)=>{
console.log(e.target.checked)
console.log(obj)
setTasks(tasks.filter(obj2=>{
if(obj2.id===obj.id){
obj2.status=e.target.checked
}
return obj2
}))
}} value={obj.status} /> </li>)}
</ul>
<h4>Completed tasks</h4>
{tasks.map((obj)=>{
if(obj.status){
return(<h5>{obj.toDos}</h5>)
}
return null
})}
</div>
);
}
}
export default Todo;
node- index.js
const lists =[
{id: new Date(),toDo:"learn react"}
]
app.post('/Todo',function(req, res){
lists.push({"id":new Date(),"toDo":req.body.list,"status":false})
console.log(lists)
res.status(200).json(lists[lists.length-1])
})
app.get('/Todo', (request, response) => response.status(200).json(lists));
req.body.list.pop()
res.status(200).json({"id":new Date(),"toDo":req.body.list,"status":false})
This will remove the last element in the list

Send Data from Span in EJS to Server Nodejs

Using Nodejs, Express, EJS
I see a lot of 'Send Data from Server to Client' but not from Client to Server AND sending the data from a tag not from a form input.
I would like to send the content of a tag from my ejs page/client to my nodejs/server.
What I'm trying...
page.ejs
<div>
<form action="/brewery" method="GET">
<div class="form-group">
<input type="text" class="form-control"
placeholder="search brewery name"
name="search">
</div>
<input class="button" type="submit" value="Submit">
</form>
</div>
<div>
<ul>
<% searchBreweryList.forEach(function(searchBrewery){ %>
<div>
<li>
Brewery Name: <span><%= searchBrewery.brewery.brewery_name %></span>
Brewery ID: <span name="brewID" id="shareBreweryID"><%= searchBrewery.brewery.brewery_id %></span>
</li>
</div>
<% }) %>
</ul>
</div>
Then on my server side...
server.js
app.get('/brewery', async (req, res) => {
var searchBreweryFound = req.query.search;
var isIndie = req.params.brewID
//console.log(isIndie)
//console.log(searchBreweryFound)
try {
request("https://api.com/v4/search/brewery?access_token=abc123&limit=1&q=" + searchBreweryFound, function (error, response, body)
{
if (error) throw new Error(error);
const searchBrewery = JSON.parse(body);
const searchBreweryList = searchBrewery.response.brewery.items.map(item => item );
res.render('brewery.ejs', {searchBreweryList});
//console.log(searchBreweryList);
});
} catch(e) {
console.log("Something went wrong", e)
}
});
So the above Get call is just an example where I'm trying to take the result in the client side span that looks like <span name="brewID">. Then I'm trying to give that ID number to the server in the var seen as var isIndie = req.params.brewID.
But this does not seem to be a method that allows me to pass content from a span in client to server.
What approach should I be taking? Thanks!
It's not clear what you mean by "sending data from client to server". Standard method of sending data from client to server is using XMLHttpRequest (XHR) inside *.js file(s), but based on your code you want to redirect browser window to URL with some parameters. When browser hit your endpoint, for example /brewery, server will render *.ejs file and respond to browser with HTML code.
Redirecting browser with EJS
Below code is based on code you posted.
<div>
<ul>
<% searchBreweryList.forEach(function(searchBrewery){ %>
<div>
<li>
Brewery Name: <span>
<%= searchBrewery.brewery.brewery_name %>
</span>
Brewery ID: <span name="brewID" id="shareBreweryID">
<%= searchBrewery.brewery.brewery_id %>
</span>
<!-- Here we create link using parameter of brewery (version with param) -->
Go to brewery
<!-- Version with query param -->
Go to brewery
</li>
</div>
<% }) %>
</ul>
</div>
After clicking Go to brewery browser will hit /brewery endpoint with param brewery_id. I also noticed that in posted example var isIndie = req.params.brewID may not work.
Bonus: req.query vs req.params
Both req.query and req.params are used to get some informations from endpoint URL. However req.query and req.params are not the same.
Using req.query
For endpoint: /brewery?id=5&q=test
const id = req.query.id // 5
const q = req.query.q // 'test'
Using req.params
To use req params you must place param name somewhere in url of express endpoint.
app.get('/brewery/:id', async (req, res) => {
var id = req.params.id
})
So to make your example with req.params working:
app.get('/brewery/:brewID', async (req, res) => {
var searchBreweryFound = req.query.search;
var isIndie = req.params.brewID
// Rest of your code
})

Jhipster : disable dialog close on submit

I am using Jhipster V3.
I have created an entity, and Jhipster generated all the needed views.
My client wants that in the update dialog of this entity, the click on Save doesn't close the popup.
I have commented one line on this function :
var onSaveSuccess = function (result) {
$scope.$emit('rhTechvalleyApp:consultantUpdate', result);
//$uibModalInstance.close(result);
vm.isSaving = false;
};
In this popup I have a datepicker component. Its value is getting blank once the save process has finished. It s only a display issue, but I don't know how to get rid of it.
If anyone knows...
Thanks.
[UPDATE]
transformResponse: function (data) {
data = angular.fromJson(data);
data.dateEnregistrement = DateUtils.convertLocalDateFromServer(data.dateEnregistrement);
data.dateDernierPointDisponibilite = DateUtils.convertLocalDateFromServer(data.dateDernierPointDisponibilite);
data.dateDisponibilite = DateUtils.convertLocalDateFromServer(data.dateDisponibilite);
return data;
}
<div class="input-group">
<input id="field_dateEnregistrement" type="text" class="form-control" name="dateEnregistrement" uib-datepicker-popup="{{dateformat}}" ng-model="vm.consultant.dateEnregistrement" is-open="vm.datePickerOpenStatus.dateEnregistrement"/>
<span class="input-group-btn">
<button type="button" class="btn btn-default" ng-click="vm.openCalendar('dateEnregistrement')"><i class="glyphicon glyphicon-calendar"></i></button>
</span>
</div>
You need to add transformResponse to the update function of the Angular service for your entity. It should be the same as transformResponse for get.
Example:
'update': {
method:'PUT',
transformResponse: function (data) {
data = angular.fromJson(data);
data.birthDate = DateUtils.convertLocalDateFromServer(data.birthDate);
return data;
}
}
The reason you need to do this is because the server will return a string like 2016-04-12 for dates. This needs to be converted to a JavaScript Date object, which is what Angular expects for type="date" inputs. If you use a string instead of a date object for ngModel on a date input, Angular will throw an error and fail to fill the field. You can use DateUtils.convertLocalDateFromServer for LocalDate and DateUtils.convertDateTimeFromServer for DateTime.

When I pass res.render object then in .ejs file it is undefined

I want to show values of post object in my profilearea.ejs file.But when it renders to profilearea.ejs then it gives an error that "post is not defined".
Here is the code in node.js
PersonalInfo.findOne({username:req.body.name}, function(err,post){
if(err || !post)
{
console.log("find is not done");
}
else
res.render('profilearea.ejs', {post:post});
}
})
This is the code in profilearea.ejs file
<section id="notification" data-role="page" >
<header data-role="header" data-theme="b"><h2>INFORMATION</h2></header>
<div data-role="content">
<p> <%= post%> </p>
</div>
</section>
I think part of the issue may be in not stringifying the object prior to rendering.
Try:
else {
var jpost = JSON.stringify(post);
res.render('profilearea.ejs', {post:jpost});
}

Resources