React: Data won't be saved to this.state - node.js

So I am trying to send a get request to my node server which is responding by sending a list of objects that I wish to display on my page.
Tried many different methods, but I cant seem to find a solution. Also I am rendering via the server if that's any help.
Client Code:
class BookTools extends React.Component {
constructor(props) {
super(props);
this.state = {
books: []
};
this.handleAdd = this.handleAdd.bind(this);
this.handleEdit = this.handleEdit.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.updateList = this.updateList.bind(this);
fetch('/getbooks').then(function (res) {
return res.json();
}).then(function (json) {
console.log(json);
const data = JSON.stringify(json);
console.log(data);
this.setState({ books: data})
});
}
Can't use componentDidMount since it's SSR and can't seem to get componentWillMount to work either, so i tried doing it in the constructor as suggested by another. both console.logs prints out the correct response.
I have also tried doing both this.setState({ books: json.body }) and this.setState({ books: json.data }) with no other result. And yes i am quite new to react as well as node/express
Thanks for any help :)

It’s common issue in react. When you use regular function this context won’t be available so either you need to bind it or change it to arrow function.
Also make sure the API returns data
Change
fetch('/getbooks').then(function (res) {
return res.json();
}).then(function (json) {
console.log(json);
const data = JSON.stringify(json);
console.log(data);
this.setState({ books: data})
});
To
fetch('/getbooks')
.then(res => res.json())
.then(json => {
console.log(json);
const data = JSON.stringify(json);
console.log(data);
this.setState({ books: data})
});
Or
fetch('/getbooks')
.then(function (res) {
return res.json();
}.bind(this))
.then(function (json) {
console.log(json);
const data = JSON.stringify(json);
console.log(data);
this.setState({ books: data})
}.bind(this));

Related

Why axios does not send request with params?

function googleFind(what,where){
var links = []
axios
axios.get(`https://www.google.com/`,{params: {
"search?q=": what,
}})
.then(res => {
fs.writeFileSync("text.html",res.data)
})
.catch(err => console.log(err))
}
googleFind("Something","znanija.org")
The code must send get request:"https://www.google.com/search?q=Something",
but it just ignored "params",
help pls
Search should be part of the URL and params should be passed as an object.
axios.get('https://www.google.com/search', {
params: {
q: what,
},
});

Axios is returning undefined

My API is returning proper data when I am requesting from Postman. Even API is getting properly called from React, I checked using console.log inside the controller, but I am always getting undefined response. I am not sure what the mistake is.
const submit = async (e: SyntheticEvent) => {
e.preventDefault();
const response = await axios
.get('certificates', {
params: { sponser },
})
.then((res) => {
console.log(response); //undefined
alert(res.status); //200
alert(res); //[object Object]
});
};
Could you please help me on the same.
You need to return res in the then to have access on response:
const response = await axios
.get('certificates', {
params: { sponser },
})
.then((res) => {
console.log(response); //undefined
alert(res.status); //200
alert(res); //[object Object]
// response is not defined here!
return res;
});
console.log(response);
Shorter way:
const response = await axios
.get('certificates', {
params: { sponser }
});
console.log(response);
It seems that OP is relatively new to js - I can recommend this intro to async js: https://javascript.info/async-await

POST request with Axios not sending data to my server

Here is my React code for the form submission:
const handleSubmit = (e) => {
e.preventDefault();
console.log('item:', item);
Axios.post('http://<MY_SERVER>/item/add', {name:item})
.then(response => console.log(response))
.catch(err => console.log(err));
};
and this is the code in my Node API:
// Add a new Item
app.post('/item/add', (req, res) => {
const newItem = new Item({
name: req.body.name
});
newItem.save()
.then(item => {
res.json({msg: 'success'});
})
.catch(err => console.log(err));
});
When I run the handleSubmit nothing happens. I only get the console.logs... Also, here is the error from my server
'ValidationError: item validation failed: name: Path' `name` is required
So it is clear that the data sent over to the api is never received. I've tried changing it up in many ways I have came across online but no luck.
I have attached both ways to post data i.e. Form URL Encoded and JSON. For sending Form Url Encoded data we need an additional Library querystring.
You can install it using npm install query-string
Here is the code for both the requests. You don't need query-string if you are using content type application/json.
Here you go
var axios = require('axios');
const qs = require('querystring');
function sendFormUrlEncodedData() {
const headers = {
'Content-Type': 'application/x-www-form-urlencoded'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with form url using querystring node package for it.
axios
.post('https://reqres.in/api/users', qs.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
function sendJSONData() {
const headers = {
'Content-Type': 'application/json'
};
const payload = {
name: 'morpheus',
job: 'leader'
};
//Send data with JSON, so stringifying it.
axios
.post('https://reqres.in/api/users', JSON.stringify(payload), {
headers: headers
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});
}
sendFormUrlEncodedData();
sendJSONData();
First of all check whether your backend code is working or not by using postman. I think you are getting validation error because of the error of your backend code. And also check whether that you are implemented the name attribute correctly with its data type.
After that update, the react code as below.
import axios from 'axios';
constructor() {
this.item = {
name: ''
}
}
handleSubmit(event) {
console.log('item:', this.item.name);
event.preventDefault();
axios.post('http://<MY_SERVER>/item/add', this.item)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}

axios does not work with while fetch does

i want to get data (array) from /{url} and i tried this code
// Fetch the list on first mount
componentDidMount() {
this.getList();
}
// Retrieves the list of items from the Express app
getList = () => {
fetch('/main')
.then(res => res.json())
.then(list => this.setState({ list }))
}
this is working fine but then i decided to switch to axios and tried literally same code
// Fetch the list on first mount
componentDidMount() {
this.getList();
}
// Retrieves the list of items from the Express app
getList = () => {
axios.get('/main')
.then(res=> res.json())
.then(list => this.setState({list}))
}
but it did not worked and gave me error in this line: .then(res=> res.json())
so i do not know what is problem if anyone knows the clue i will be glad if you tell me
// Fetch the list on first mount
componentDidMount() {
this.getList();
}
// Retrieves the list of items from the Express app
getList = () => {
axios.get('/main')
.then(res=> res.data)
.then(list => this.setState({list}))
.catch(error => this.setState({error: error.message}))
}
It is because axios has different response, instead of res.json() return data already like : return res.data or pass it to state directly something like
getList = () => {
axios.get('/main')
.then(res=> this.setState({list: res.data}))
i would recommend some changes in your design, as im using axios successfully in many projects, its not a requirement but it helps and is working very reliable:
Create a service like api.js
import axios from 'axios';
export default axios.create({
baseURL: `http://my.api.url/`
});
Then you can use it like this
import API from '../Services/api'; // this is your service you created before
LoadStats = async event => {
try {
var response = await API.get('api/targetroute');
if (response.data != null) {
this.setState({
stats: {
mydata: response.data
}
});
console.log('Receiving result: '+JSON.stringify(response.data));
}
} catch (error) {
console.log('ERROR: '+error)
}
}

Sending a String from Node Js to a component React Js

i am using Node Js and React Js to send data from node to a React component but the state never change in the console when i did response.json() i get my string sent but in my component it's empty and there is no data .
Here is my Node js code :
app.post('/try', function(req, res) {
results='hello everybody !'
res.send(JSON.stringify(results));
});
And here's my React component:
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = { results: null };
}
componentDidMount() {
const data = new FormData();
fetch('http://localhost:4000/try',{
method: 'POST',
body : data
})
.then(
(response) => {
console.log(response);
return response.json();
} // if the response is a JSON object
).then(
success =>console.log(success) // Handle the success response object
).catch(
error => null // Handle the error response object
)
.then(results => {
this.setState({ results: results });
console.log(results)
});
}
render() {
return (
<div className="Users">
<h1>results</h1>
<div>this is my result: {this.state.results}</div>
</div>
);
}
}
export default App;
First of all, results is string, you dont have to convert it to string again,
results='hello everybody !'
then, in react you are not using the proper way of thens. Please try the below code.
fetch('http://localhost:4000/try', {
method: 'POST',
body: data
})
.then((response) => {
console.log(response);
response.json().then((result)=>this.setState({ results: results }))
}
.catch(
error => null // Handle the error response object
)
You can't convert the normal string to JSON.
eg.
var result = "hello everybody !"
console.log(JSON.stringify(result)); // ""hello everybody !""
This is not a JSON
Try this way
var result = {"data" :"hello everybody !"}
console.log(JSON.stringify(result)); // "{"data":"hello everybody !"}"

Resources