Response returning undefined react js axios - javascript

I trying to view status of a variable (salesforecasting) in database. Its responds by sending true or false which is received fine in Postman. However when it gets to react, it is shows undefined on console. if i see whole response object, there i can see value has return correctly but when i try to print it, it shows undefined.
in routes/api/salesforecasting.js
router.post('/view', function(req, res) {
const email="Hamzakhan003#gmail.com"
Customer.findOne({Email:email})
.then(data=>{
if(data){
let salevalue=data.Salesforecasting
res.send({
value: salevalue
});
}
});
});
in react file
componentDidMount(){
return axios.post('http://localhost:3000/api/sales-forecasting/view')
.then(response => {
//const output = response.value
const value = response.value;
{console.log(arr.value)}
this.setState({
added: value
});
});
}

I think u need to check in response.data.value instead of response.value.
axios populates the entire server response in response.data

Related

Access Value from One Function and Pass Into Another Function Using Express Post Request

So I have these functions and passing the value into another function works fine with regular javascript functions. My problem is passing this same value through post request on express.
Here is the regular JS functions without express that currently works
Inside of one file called quote.js I have this code that generates a random ID
export const response = await client.deliveryQuote({
external_delivery_id: uuidv4(),
});
console.log(response);
Then in another file called quoteNew.js I have this code which receives the value from the quote.js file and gets the external_delivery_id value
import { response } from "./quote.js";
const response1 = client
.deliveryQuoteAccept(response.data.external_delivery_id)
.then((resp) => {
console.log(resp);
})
.catch((err) => {
console.log(err);
});
console.log(response1);
So this code above works perfectly fine when getting the external_delivery_id value.
Now what I want to do is replicate this same thing except using express.
So in my server.js file I have this code. When I add this code response.data.external_delivery_id into the deliveryQuoteAccept it doesn't work the same and says response is not defined since it can't access the response value from the app.post get-quote function
Right now it just says response is not defined when passing it into the 2nd app.post function
app.post("/get-quote", async (req, res) => {
const response = await client.deliveryQuote({
external_delivery_id: uuidv4(),
});
res.send(response);
});
app.post("/accept-quote", (req, res) => {
const response1 = client
.deliveryQuoteAccept(response.data.external_delivery_id) //response is not defined
.then((response) => {
console.log("Delivery Created", response);
})
.catch((err) => {
console.log(err);
});
console.log("ACCEPT", response1);
})
How do I access the response value from the first app.post function and transfer it into my 2nd app.post function in this section
const response1 = client
.deliveryQuoteAccept(I NEED THE EXTERNAL_DELIVERY_ID VALUE HERE)

API data won't convert to JSON format

Had the data in JSON in a previous build of my app but (with the help of StackOverflow community) redesigned how I call my API to fix various other breaking errors.
This is what I just tried. I log both the "regular" output and the attempt at converting it to JSON. The non-json output comes up as "{data: Array}" in my console while the JSON is undefined.
componentDidMount() {
axios
.get(
"API_KEY"
)
.then((res) => {
const data = res.data
const json = data.json
this.setState({ data, loading: false });
console.log(json);
console.log(data)
});
}
And here is my other attempt:
componentDidMount() {
axios.get("API_KEY").then((res) => {
const data = res.data;
this.setState({ data, loading: false });
console.log(data);
console.log(JSON.parse(JSON.stringify(data)));
});
}
All your help and advice is greatly appreciated! :)
I would suggest a better syntax using ES6.
const componentDidMount = async () => {
let { data } = await axios.get("API_KEY")
// Your data by default should be object or array.
// Regardless, both should worked fine.
console.log(data)
// In case it is just string and not undefined
if (data && typeof data !== 'object') {
data = JSON.parse(data)
}
this.setState({ data, loading: false })
}
Otherwise, try using breakpoint or console.log in the first place after getting the result. If the result is undefined, perhaps the promise is yet to resolve.

loglevel-plugin-remote keeps sending the same request to the API continuously

I have a React application that uses loglevel-plugin-remote, as well as a custom API endpoint to receive the logs for error monitoring.
My log configuration is
import log from 'loglevel';
import remote from 'loglevel-plugin-remote';
const customJSON = log => ({
message: log.message,
level: log.level.label,
stacktrace: log.stacktrace
});
if (process.env.REACT_APP_SEND_LOGS === 'true') {
const apiPath = `${process.env.REACT_APP_API_PATH}/log`;
remote.apply(log, {
format: customJSON,
url: apiPath,
stacktrace: {
depth: 10
}
});
}
export default log;
And an example call is
import log from '../utils/logger';
...
const getUserData = () => {
return axios({url: userApi, method: 'GET', headers: authContext.authorizationHeaders })
.then(response => response.data)
.catch(error => {
log.error(error);
})
};
However, when the log gets called once, it will continually send requests to the API until I finally refresh the page.
The problem appeared to be with loglevel-plugin-remote which only checks to see if there's a 200 success status code response from the API, or else it will keep trying indefinitely.
My API, however, was returning a 201 message which I thought made more sense for creating a log entry. But when I changed the response to 200, I no longer had the issue. It appears to be an open issue with the repo, but hopefully, this helps others if you're seeing the same thing.

How do I get data from Express endpoint in a React component?

I have a simple react component and express endpoint that returns the string "sample data". I'm just trying to hit that endpoint in my react app and store the text in state and display it on the screen.
My component:
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
this.callBackendAPI()
.then(res => this.setState({ data: res.data }))
.catch(err => console.log(err));
}
async callBackendAPI() {
const response = await fetch('/sampleData');
const body = await response.json();
if(response.status !== 200) {
throw Error(body.message)
}
return body;
}
render() {
let data = this.state.data || 'there is no data';
return (
<div className="App">
<header className="App-header">
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">{data}</p>
</div>
);
}
}
export default (App);
The backend endpoint:
app.get('/sampleData', function(req, res) {
res.send('sample data');
});
I'm not sure I need response.json() since the endpoint just returns plain text, I actually get an error with this code SyntaxError: Unexpected token s in JSON at position 0. When I just use response nothing happens and the text just shows up as "there is no data" since the state is empty.
How can I get the text from my endpoint into the components state and displayed on screen?
Thanks!
response is a Response object. fetch will give you access to it when the HTTP response header has been read, not the response body - this is why you have to await on response.json(), as you can't parse the body data until it has finished transferring.
This same principle applies when reading plain text from a Response - you need to await on response.text(), to allow the response to finish being read. In this case, you'll also need to amend your setState and Error , as body will just be a string, not an object.
This might all seem a bit unintuitive, but it's for good reason - because you get a Response as soon as the response starts being transferred, you can take actions based on the status/HTTP headers while the rest of the response is still loading.
My guess is that your endpoint does not have the res.data in the response.
I would recommend throwing a console.log(res) in your .then() to see what is returned - if nothing is returned, I would double check you are returning on the url provided.
Your code looks fine, I tested it quick and it looks good to me, it was just a matter of getting the response data correctly.
I think your error is here:
app.get('/sampleData', function(req, res) {
res.send('sample data');
});
you send a text not a Json so when you try to receive data with
const body = await response.json();
you have that error.
so you can change your back-end and send Json object as
app.get('/sampleData', function(req, res) {
res.send({text:'sample data'});
});
or as Joe Clay had suggest you, you can receive text with
const body = await response.text();

Get request yields response with data in it, but when accessing .data specifically it yields undefined

Apologies if the terminology is not great, still new to fullstack.
Hello! I am trying to get all the users in my DB. The get() response is OK as the client is receiving the response (see image below)
The problem is that when I try to fetch the .data I get undefined.
Here's my Vue Component
import UserService from '#/services/UsersService.js'
export default {
data () {
return {
users: null
}
},
async mounted () {
// GET request for all users.
this.users = UserService.index().data
console.log('The response is OK', await UserService.index())
console.log('when trying to fetch the .data I am getting ', await this.users)
}
}
The index() function
import Api from '#/services/Api'
export default {
index () {
return Api().get('users')
}
}
Everything works fine, except that I get undefined data...
I think you forgot to fetch the data asynchronously?
async mounted () {
// GET request for all users.
- this.users = UserService.index().data
+ const res = await UserService.index()
+ this.users = res.data
console.log('The response is OK', await UserService.index())
console.log('when trying to fetch the .data I am getting ', await this.users)
}
You correctly use await syntax in the first console.log, which might explain why the data return correctly.

Categories

Resources