Axios Chaining. Cloudinary Upload -> Express -> MSQL save - mysql

My second axios call requires const { secure_url } = res.data from the first axios call.
I use the secure url to store in my database with another axios call.
await axios.post(details.upload, formData, {
onUploadProgress: ProgressEvent => {
setUploadP(parseInt(Math.round((ProgressEvent.loaded * 100) / ProgressEvent.total)))
setTimeout(() => setUploadP(0), 3000);
}
})
.then((res) => {
const { secure_url } = res.data;
axios.post('https://foodeii.herokuapp.com/api/insertRecipe', { values: inputValue, userID: props.userID, img: secure_url }).then((response) => {
console.log('Recipe added successfully.')
goBack();
})
})
.catch((err) => {
console.log(err);
})
The second axios call works fine with uploading the data, but I get a timeout, the console log doesn't fire either. My Express insert function is really small so I do not understand why it timeouts.
// INSERT
app.post('/api/insertRecipe', (req, res) => {
const data = req.body.values;
const uID = req.body.userID;
const img = req.body.img;
const sqlInsert = "INSERT INTO recipes (uID, NAME, INGREDIENTS, INSTRUCTIONS, IMAGE) VALUES (?,?,?,?,?)";
db.query(sqlInsert, [uID, data.theName, data.ingredients, data.instructions, img], (err, result) => {
console.log(err);
});
})
My Server runs on Heroku, while the React frontend is on netlify.
The server error is 'code=H12' when the timeout occurs.
Thank you

Related

How to pass updated set State value in axios request as params

I'm a beginner in react native, I'm trying to get user information from mysql database through an axios API get request.
Once logged in, I stored email address in AsyncStorage and later want to use that email address from AsyncStorage as params or parameters to get the user details.
I wrote a code which set initial state of the setState as 'na'. Please help me how I can pass the email address from AsyncStorage as params or parameters.
Here is my code.
// to load email address
const [SessionEmail, setSessionEmail] = useState('na');
// to load users info
const [users, setUsers] = useState([]);
useFocusEffect(
React.useCallback(() => {
getUsername();
getUsersInfoFromAPI();
}, [])
);
// to get the session username from localstorage
const getUsername = async () => {
try {
const username = await AsyncStorage.getItem('Username')
if (username !== null) {
setSessionEmail(username);
}
} catch (e) {
console.log(e);
}
}
// API Calling user details
const getUsersInfoFromAPI = async () => {
await axios.get(`https://myapi.co.in/api/user/?email=${SessionEmail}`)
.then(response => {
setUser(response.data);
})
.catch(error => {
console.log(error);
});
}
After the page is rendered, and I load page from metro, I can see the parameters have been sent to server.
Update your code in this way:
useFocusEffect(
React.useCallback(() => {
getUsername();
}, [])
);
Instead of saving your email to state, sent it to function directly but if you are using it for other reason you can still save it but call function while getting username from AsyncStorage with username parameter like below.
// to get the session username from localstorage
const getUsername = async () => {
try {
const username = await AsyncStorage.getItem('Username')
if (username !== null) {
getUsersInfoFromAPI(username);
}
} catch (e) {
console.log(e);
}
}
// API Calling user details
const getUsersInfoFromAPI = async (email) => {
await axios.get(`https://myapi.co.in/api/user/?email=${email}`)
.then(response => {
setUser(response.data);
})
.catch(error => {
console.log(error);
});
}
const [users, setUsers] = useState([]);
here you can use like this
const [users, setUsers] = useState();
hope this will help you

Mongoose updating and fetching in the same request

I have the following mongoose "update" path:
app.put('/update', async (req, res) => {
const newTaskName = req.body.todoName
const newDays = req.body.days
const id = req.body.id
try {
await TodoModel.findById(id, async (err, updatedTodo) => {
updatedTodo.todoName = newTaskName
updatedTodo.daysToDo = newDays
await updatedTodo.save()
res.send("updated")
})
} catch(err) {
console.log(err)
}
})
Separately I have a path that returns all data from the Mongo table:
app.get('/read', async (req, res) => {
TodoModel.find({}, (err, result) => {
if (err) {
res.send(err)
}
res.send(result)
})
})
How can I both update and send back the full updated list within the response?
Separate question, not necessary to answer, but would be nice - perhaps this approach is all wrong? some background:
In my MERN app I am calling to add an item to a list and then want to immediately render the updated list as currently read from the database, since I don't want to assume the insertion was successful
I tried using some asynchronous workarounds with no luck
Fixed!
Upon further inspection of Mongoose documentation, I found that by using the findOneAndUpdate method instead of findById, I am able to utilize a callback that will return the updated item:
app.put('/update', async (req, res) => {
const id = req.body.id
let updateSet = req.body
delete updateSet.id
try {
ShoppingModel.findOneAndUpdate({ _id: id }, { $set: updateSet }, { new: true }, (err, doc) => {
if (err) return console.log(err)
res.send(doc)
})
} catch (err) {
console.log(err)
}
})

Getting empty {} from mysql table, on React and node.js

For some reason am getting empty object back from mysql table, the table is filled in with some vacation detail. And i want to display them with map in my react app.
On the client side am doing the request with useEffect state and axios.
useEffect(() => {
axios.get("http://localhost:3001/vacations")
.then((response) => {
let vacationsResponse = response.data;
dispatch({ type: ActionType.GetAllVacations, payload: vacationsResponse })
}).catch(err => {
console.log("Failed to get data" + err)
})
}, [dispatch])
this is the server side:
const vacationsControllers = require("./Controllers/vacationsControllers");
const cors = require("cors");
server.use(cors({ origin: "http://localhost:3000" }));
server.use("/users", usersController);
server.use("/vacations", vacationsControllers);
server.listen(3001, () => console.log("Listening on http://localhost:3001"));
this is the vacationsControllers folder:
router.get("/", async (request, response) => {
let vacationsData = request.body;
try {
await vacationsDao.getAllVacations(vacationsData);
response.json();
console.log(vacationsData) *get this empty in the node terminal*
} catch (e) {
console.error(e);
response.status(600).json();
}
});
module.exports = router;
The sql execute (the vacationDao folder):
let connection = require("./connection-wrapper");
async function getAllVacations(vacationsData) {
const sql = `SELECT * FROM current_deals`;
await connection.executeWithParameters(sql);
return vacationsData;
}
module.exports = {
getAllVacations,
};

single-spa axios calls redirecting to single-spa port

I am trying out single-spa and is stuck with the below issue
I have single spa running on port 5000 and 2 apps running on port 8081 and 8082.
The apps were already running applications converted to single-spa. The apps have axios calls to get data from the server.
After the migration, the Axios calls uses the URL http://localhost:5000/json/xxx.json where it should have been http://localhost:8081/json/xxx.json
How can I get this issue fixed? How can I make sure that each application calls its own backend and not single spa?
sample axios call
return new Promise((resolve, reject) => {
axios.get('/json/xx.json', {
responseType: 'json'
})
.then((response) => {
resolve(response.data)
})
.catch(reject)
.finally(() => {
doSomething()
})
})
You can use env variables for your axios url instead of setting them with relative path.
function getAxiosInstanceFor(baseURL: string):{
return axios.create({
baseURL,
timeout: 20000,
})
}
// App1.js
// Do same thing to get api/App2.js resource.
const APP1_BASE_URL = process.env.APP1_BASE_URL;
axiosInsance = getAxiosInstanceFor(APP1_BASE_URL );
function get(path: string){
return new Promise((resolve, reject) => {
axiosInsance.get(`${path}`, {
responseType: 'json'
})
.then((response) => {
resolve(response.data)
})
}
.catch(reject)
.finally(() => {
doSomething()
})
})
export const { get };
// somewhereElse.js
// call functions like so
import App1 from 'App1.js';
import App2 from 'App2.js';
App1.get("/json/xx.json")
App2.get("/json/xx.json")

Nodejs & sequalize mysql query to the database happens only once

I have the following node code,i am trying to query the database based on a request,i use sequelize orm with mysql
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const axios = require("axios");
const models = require("./models");
const jsonParser = bodyParser.json();
app.post("/auth/change", jsonParser, (req, res) => {
let phoneNumber = req.body.phone;
let password = req.body.password;
console.log("phone number", phoneNumber);
models.users
.findOne({
where: {
phone: phoneNumber
}
})
.then(user => {
console.log(user.name);
}).catch(error => {
console.log(error);
});
});
app.listen(3000, () => {
console.log("Listening on port 3000");
});
I use react on the front end, and when i send a request with data for example
{phone:777,password:123} it works, but if i do a second request with same or different data it fails.What am i missing here!!?
you are not returning any data to the front side when it call the API , so the server will be waiting to return a response to the caller.
try to change your code to this :
models.users
.findOne({
where: {
phone: phoneNumber
}
})
.then(user => {
res.status(200).send('ok')
}).catch(error => {
res.status(400).send('not ok')
});