Initial fetch get request slow using React, Express - reactjs

In a simple react set up with express, the very first fetch get request is too slow. The get requests following it seem normal speed.See the first /api/passages/happiness in the log below with a time of 33+ milliseconds.
Basic order of operations:
button click triggers GET request from local Express server
sets state with the data
calls an external API through a proxy url
displays that data in a modal
I'm new at speed/performance issues. Where do I begin troubleshooting? Or which step is likely slowing it down?
// onClick of button, these steps occur:
handleOpen = () => {
// 1. call express api, returns a few lines of text
baseService.get(`/api/passages/${this.props.document}`)
.then(data => {
this.setState({
reference: data.reference,
abbr: data.abbr,
start: data.start,
end: data.end
})
})
.catch(err => {
alert("Verse failed to load")
console.log(err)
})
// 2. call external api, returns a few lines of text
.then(() => {
const url = `https://bibles.org/v2/chapters/eng-NASB:${this.state.abbr}/verses.js?start=${this.state.start}&end=${this.state.end}`
fetch(proxyurl + url, {
headers: new Headers({ 'Authorization': 'Basic ' + window.btoa(`${BIBLE_API_KEY}: x`) }),
redirect: "follow",
})
.then(res => res.json())
.then(contents => {
let versearray = contents.response.verses
versearray.forEach(verse => {
var regex = /(<([^>]+)>)|[0-9]/ig;
let versetext = verse.text.replace(regex, "");
let alltext = this.state.content.concat(' ', versetext)
this.setState({
content: alltext,
// 3. open modal displaying few lines of text
open: true
})
})
})
})
.catch(err => {
alert("Your Verse Failed to Load");
console.log(err)
})
};
config
let mongoose = require('mongoose');
const server = '127.0.0.1:27017'
const database = 'verseapp';
class Database {
constructor() {
this._connect()
}
_connect() {
mongoose.connect(`mongodb://${server}/${database}`, {
useNewUrlParser: true,
useCreateIndex: true,
})
.then(() => {
console.log('Database connection successful')
})
.catch(err => {
console.log('Database connection error', err)
})
}
}
module.exports = new Database()

Related

MongoDB / ReactJS Patch handler / findOneAndUpdate not working

in the following code, I'm attempting to update the Checkpoints field for one of my objects within the projects collection. UpdatedCheckpoints is working correctly, so I believe the first block of code works. But the change isn't logging to the database so it doesn't persist. What's going wrong?
const onApprovedSubmit = useCallback(
async (e) => {
e.preventDefault();
let updatedCheckpoints = props.project.Checkpoints;
updatedCheckpoints[props.checkpointIndex].checkpointSubmitted = true;
console.log('here');
try {
let projectId = props.project._id;
await fetcher('/api/projects', {
method: 'PATCH',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify({ Checkpoints: updatedCheckpoints }),
id: projectId,
});
toast.success('Your checkpoint has been updated');
} catch (e) {
toast.error(e.message);
}
},
[props],
);
handler.patch(async (req, res) => {
const db = await getMongoDb();
const project = await updateProjectById(db, req.id, req.body);
res.json({ project });
});
export async function updateProjectById(db, id, data) {
return db
.collection('projects')
.findOneAndUpdate(
{ _id: new ObjectId(id) },
{
$set: data,
},
{ returnDocument: 'after' },
)
.then(({ value }) => value);
}

Getting SignalR unauthorized error in ReactJS

I have created signalR connection in my ReactJS application, whenever i load page for the first time then i get an error "Error: Failed to complete negotiation with the server: Error: Unauthorized" but when i reload the page again then it works fine i.e. it get connected properly.
I just want to connect the signalR connection properly when page load for the first time without the need to reload it again
Here is my code for signalR connection:
export default class Dashboard extends Component {
constructor(props) {
super(props)
this.state = {
signalRURL: 'https://****/?hub=broadcast',
accessToken: '',
alertData: {}
}
}
getURL = () => {
return new Promise((resolve, reject) => {
return axios({
url: 'https://*****/api/SignalRConnection',
method: "get",
headers: {
"content-type": "application/json",
"Access-Control-Allow-Origin": "*"
},
})
//Get the SignalR connection information which contains Url and Access token,
//by calling the SignalRConnection API.
.then(response => {
localStorage.setItem("access_key", response.data.accessToken)
console.log("response", response)
resolve(response);
})
.catch(error => {
reject(error);
});
});
}
componentDidMount = () => {
this.getURL().then(data => {
console.log("dataaa", data)
})
.catch(err => {
console.log("error", err)
})
//Create the Hub connection using SignalR.HubConnectionBuilder.
const options = {
accessTokenFactory: () => localStorage.getItem("access_key")
};
const hubConnection = new SignalR.HubConnectionBuilder()
.withUrl(this.state.signalRURL, options)
.configureLogging(SignalR.LogLevel.Information)
.build();
hubConnection.on('notify', data => {
this.setState({alertData: data})
console.log("state data",this.state.alertData)
console.log(data);
});
hubConnection
.start()
.catch(
error => console.error(error)
);
hubConnection.serverTimeoutInMilliseconds = 6000000;
hubConnection.keepAliveIntervalInMilliseconds = 3000000;
hubConnection.onclose((error) => {hubConnection.start();
console.error(`Something went wrong: ${error}`); });
}
render() {
return (
<div>
</div>
)
}
}
This is the error message i get everytime when i load the page for the first time

When I fetch(url).then(console.log), the console.log does not execute

Hi I've been in a limbo with the problem. I'm trying to use the update method to update the iterations of clicks in my URL shortener project. The iterations update in the DB but then it isn't reflecting on the front end. I was thinking it would update in the then() function after fetching but then it seems like it didn't go in the then() function. My question is that is there something wrong with the code or is there an alternative way for it to get to the then()?
Client side (React)
const id = record._id;
fetch(`http://localhost:3001/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
.then((res) => { <-- Not executing :(
console.log("Update");
// function to refresh the page
handleRefresh();
})
.catch((err) => {
console.log(err);
});
Server side (Mongoose)
urlControllerRouter.post("/update/:id", (req, res) => {
const id = req.params.id;
UrlModel.findById(id)
.then((updateURL) => {
updateURL.click = req.body.click;
updateURL
.save()
.then(() => {
console.log(`[UPDATE] ${updateURL}`);
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
});
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
});
});
Your server isnt making a response after getting the request from the client so the connection is pretty much in limbo for lack of a better word.
You need to send a response to client
urlControllerRouter.post("/update/:id", (req, res) => {
const id = req.params.id;
UrlModel.findById(id)
.then((updateURL) => {
updateURL.click = req.body.click;
updateURL
.save()
.then(() => {
console.log(`[UPDATE] ${updateURL}`);
res.status(200).json({
message: updateURL
})
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
res.status(500).json({
message: err.message
})
});
})
.catch((err) => {
console.log(`[UPDATE] ${err}`);
res.status(200).json({
message: err.message
})
});
});
Btw, with fetch you need to add two thens to get the data you want.
But in your case you don't want to get the data so one would do
So something like this
fetch(`http://localhost:3001/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})
.then(response => response.json())
.then((res) => { <-- Not executing :(
console.log("Update");
// function to refresh the page
handleRefresh();
})
.catch((err) => {
console.log(err);
});
Also you should actually add the backend link as a proxy value to your package.json as a better way of making the API call to the backend.
"name": "",
"version": "",
"main": "",
"proxy": "http://localhost:3001", //note the proxy
"license": "",
....
Then you just need to do this with fetch
fetch(`/update/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(updateData),
})

Undefined 404 and React Hook useEffect has a missing dependency

I have a super cute site for flower-fans where you can find a profile of a flower (a mock api), read some info and put a note on each and every flower. Though, I'm not able to make the note stick anymore. So frustrating as it worked a while ago. I have updated the dependencies and also the settings for deploying on Netlify. In Postman I get the same message as in the console, which is not found 404.
I get a message in Terminal that the React Hook useEffect has a missing dependency (flowerId) too.
Down below you'll see the error message and here is a link to my deployed site:
https://flowerinspoapi.netlify.app/
Error message from Console
GET https://flowerinspoapi.netlify.app/flowers/undefined 404
Code from Flowerinfo.js
// Fetching the comments for the flowers
const url = "https://flowers-mock-data.firebaseio.com/comments/TheresaUlwahn"
export const FlowerInfo = () => {
const { flowerId } = useParams()
const [flower, setFlower] = useState([])
const [flowerMessages, setFlowerMessages] = useState([])
const [postedMessage, setPostedMessage] = useState("")
// Fetching the ID of the flowers
useEffect(() => {
fetch(`https://flowers-mock-data.firebaseio.com/flowers/${flowerId}.json`)
.then((res) => res.json())
.then((json) => {
setFlower(json)
})
}, [flowerId])
// Fetching the messages
useEffect(() => {
fetch(`https://flowers-mock-data.firebaseio.com/comments/TheresaUlwahn/${flowerId}.json`)
.then((res) => res.json())
.then((json) => {
console.log('All messages for the flower: ', json)
if (json !== null) {
setFlowerMessages(json)
}
})
}, [postedMessage])
const handleFormSubmit = (flowerId, message) => {
// console.log('POST THIS MESSAGE: ', message, 'FOR THE FLOWER: ', flowerId);
fetch(url + `/${flowerId}/.json`, {
method: "POST",
body: JSON.stringify({ message }),
headers: { "Content-Type": "application/json" }
})
.then(() => {
console.log('posted !')
// window.location.reload();
setPostedMessage(message)
})
.catch(err => console.log("error:", err))
}
var result = Object.keys(flowerMessages).map(function (key) {
return [key, flowerMessages[key]];
});

Is there something missing in this code ? I am unable to post through axios post request

So I have setup a form for taking user details and setting the data to the state. Then I am passing the state data to the database through onSubmit function. I am using axios.post request to the local host server.
My get request seems to be working fine however the data is not being posted after submitting the form.
My code looks something like this. (I am abstracting unnecessary code.)
UserForm.jsx
class UserForm extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
contact: "",
company: "",
mail: "",
key: {
wedding: false,
MICE: false,
corporate: false
},
app_no: "",
items: "",
isLoaded: false
};
}
handleSubmit = e => {
console.log("Submitted");
e.preventDefault();
const users = {
name: this.state.name,
contact: this.state.contact,
company: this.state.company,
mail: this.state.mail,
key: this.state.key,
app_no: this.state.app_no
};
axios
.post(
"http://localhost:5000/api/items",
{ users },
{
headers: {
"content-type": "application/json"
}
}
)
.then(console.log("Axios post is working"))
.then(res => {
console.log("Something: " + res);
console.log(res.data);
})
.catch(err => {
console.log(err);
});
console.log("Users; " + users.name);
};
componentDidMount() {
fetch("http://localhost:5000/api/items/", {
headers: {
"content-type": "application/json"
}
})
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
});
});
console.log(this.state.items);
}
My form seems to be working fine and giving all the items on console.
This is my items.js file:
const express = require("express");
const router = express.Router();
// Item model
const Item = require("../../models/Item");
// Routes
// #get API item get all items
// make a get req
router.get("/", (req, res) => {
Item.find().then(items => res.json(items));
});
// #get Api item POST all items
// make a post req
// create an item
router.post("/", (req, res) => {
const newItem = new Item({
name: req.body.name,
contact_no: req.body.contact_no,
company_name: req.body.company_name,
key: req.body.key
});
newItem.save().then(item => res.json(item));
});
// #del api item.
// delete request
router.delete("/:id", (req, res) => {
Item.findById(req.params.id)
.then(item => item.remove().then(() => res.json({ success: true })))
.catch(err => res.status(404).json({ success: false }));
});
module.exports = router;
Is there something I am missing in the code. I have gone through most of the axios documentation and can't seem to find the problem.
server.js
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
const items = require("./routes/api/items"); // Contains all the api routes
// Body Parser middleware
app.use(bodyParser.json());
// DB config
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("Mongo is laoded"))
.catch(err => console.log(err));
app.use("/api/items", items); // redirecting api routes to items
const port = process.env.PORT || 5000;
app.listen(port, () => console.log("Server started"));
Let me know if I should post more code..
Edit: I am not getting "console.log("Something: " + res);
console.log(res.data);" response on console.
My console prints :
(2) [{…}, {…}]
Submitted
UserForm.jsx:56 Axios post is working
UserForm.jsx:70 Users; someuser
I don't believe you'd ever be able to get your records through req.body.name, as your POST request seems to be putting that under req.body.users.name, so basically you'd want to fetch your data from req.body.users
Maybe it is beacause your second .then in axios.post
Put everything in a single .then
Try this:
.then((res) => {
console.log("Axios post is working")
console.log("Something: " + res);
console.log(res.data);
})

Resources