While trying to fetch data from my express backend and MySQL database, with my react frontend using axios, it fails to set the fetched data using useState
my frontend function looks like this
const searchUser = () => {
Axios.post("http://localhost:3001/searchUser", {
username: username,
}).then((response) => {
if (response.data) {
setResult(response.data);
}
});
};
and my backend function looks like this
const searchUser = (req, res) => {
const keyword = req.body.username;
db.query(
"SELECT id,username FROM users WHERE username like ?",
"%" + keyword + "%",
(err, result) => {
if (err) {
res.json({ message: err });
console.log(err);
} else {
console.log(result);
res.json({ result });
}
}
);
};
I tried many methods while saving the data with the useState hook, I appreciate any help
While using Promises and then instead of async / await make sure to catch the errors if your fetch fails.
Unless you share with us the whole component that contains the searchUser function and how you defined the state i cannot pin point you on the error.
What i suggest you to do is adding a catch to your fetch by doing the following:
const searchUser = () => {
Axios.post("http://localhost:3001/searchUser", {
username: username,
}).then((response) => {
if (response.data) {
setResult(response.data);
}
}).catch((error) => {
console.error(error);
});
};
If any abnormalities has happened in your request the catch will tell you! Don't underestimate it's power.
Another path you can look into is console logging your output in front end searchUser function just before setting it in the state.
I did solve the problem, just by replacing res.json({ result }); to res.json(result); in the last line in my backend function
Related
I am trying to update user data using firebase function, it's working fine when update user display name. My issue here is below function not updating the user password through firebase function.
exports.updateUserPassword = functions.https.onCall(async (data, context) => {
try {
return await authAppAdmin.auth().getUserByEmail(data.email)
.then((userPassUpdate) => {
console.log(userPassUpdate.uid);
return authAppAdmin.auth().updateUser(userPassUpdate.uid,
{
password: data.newPassword,
displayName: data.displayName
});
})
.catch((error) => console.log(error["message"]));
} catch (error) {
return error;
}
});
Many thanks in advance.
Can you try the following code? I have doubts it will solve your problem but I think we should give a try. If you still get the same problem I'll delete this answer.
It is important that you copy the three first lines and use admin.auth().... Also this code should normally correctly log any error.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.updateUserPassword = functions.https.onCall(async (data, context) => {
try {
const userPassUpdate = await admin.auth().getUserByEmail(data.email)
console.log(data.newPassword);
console.log(userPassUpdate.uid);
await admin.auth().updateUser(
userPassUpdate.uid,
{
password: data.newPassword,
displayName: data.displayName
});
return { result: "OK" }
} catch (error) {
console.log(error);
throw new functions.https.HttpsError('internal', JSON.stringify(error)); // See https://firebase.google.com/docs/functions/callable#handle_errors
}
});
I am working on a React App, and i'm trying to get some data using an axios GET request from my node backend.
the Api Endpoint i'm currently using that regard this problem is the following:
// NodeJS Backend
app.get('/v1/companys/user/:user_uuid', verify, (req, res) => { // GET - Company by User UUID
const selectQuery = 'SELECT * FROM companys WHERE uuid = (SELECT company_uuid FROM users WHERE uuid = ?)';
connection.query(selectQuery, [req.params.user_uuid], (err, results) => {
if(err) {
res.send(err)
} else if (results.length === 0) {
res.json({status: 404, message: 'Company not found'})
} else {
res.json({data: results})
}
});
});
This is my Front End:
// ReactJS FrontEnd
const companyLogo = userCompany ? userCompany.logo_url : null;
console.log(userCompany);
useEffect(() => {
const getUserCompany = async () => {
try {
await axios.get(process.env.REACT_APP_API_URL + 'companys/user/' + userUuid).then((response) => {
console.log("response "+ response);
let res = response.data.data[0];
console.log(res);
setUserCompany(res);
});
} catch (error) {
console.log(error);
}
};
getUserCompany();
}, [userUuid]);
There app works fine, but on the console the following error appear:
The object below the error is in fact the thing that i need (companyLogo)
I was wondering if someone know what am I doing wrong on my frontend to fix the TypeError.
Thanks for the help!
If you use optional chaining (?.) to catch possible null/undefined values, you'll most likely fix the issue.
So like this: let res = response.data.data?.[0];
I'm trying to update data from ui but data does not update though it can be done using postman and in payload data is also being passed.
Here is handle submit function:
enter code here
data.append("thingsTodo", values.thingsTodo);
data.append("minDaysToSpent", values.minDaysToSpent);
data.append("usp", values.usp);
data.append("geoRegion", values.geoRegion.value);
data.append("altitude", values.altitude);
data.append("thingsToConsider", values.thingsToConsider);
try {
const response = await axios.put(`/api/place/${id}`, data).then((data)=>console.log(data,"data"));
controller:
exports.updatePlace = async (req,res) => {
try {
let place = Place.findById(req.params.id)
if(!place){
return res.status(404).json({success:false,message:"Place does not exists"})
}
console.log(req.body)
place = await Place.findByIdAndUpdate(req.params.id,req.body,{new:true})
res.status(200).json({
success:true,
message:"Place Updated Successfully",
place
})
} catch (error) {
return res.status(500).json({
success:false,
error:error.message
})
}
}
my request is good but i want to know how can i use my response in React.
SQL request :
```
exports.countAllComments = async (req, res) => {
const pId = req.params.id;
db.query(
"SELECT COUNT(*) FROM comments WHERE post_id = ?",
[pId],
(err, count) => {
if (err) {
res.status(500).json({ err });
console.log(err);
} else {
console.log(count)
res.status(200).json(count);
}
}
);
};
```
Front for fetch count:
```
const [countData, setCountData] = useState(0);
useEffect(() => {
const fetchCount = async () => {
try {
const fetchData = await Axios.get(
`http://localhost:3001/api/post/comment-count/${post.id}`,
{
headers: { Authorization: `Bearer ${test1.token}` },
}
);
setCountData(fetchData.data[0]);
} catch (err) {}
};
fetchCount();
}, [post.id, test1.token]);
console.log(countData);
```
console log return : "{COUNT(*): 4}" how can i get (4)
given your trivial example, the trivial solution would be something like -
fetchData.data[0]['COUNT(*)']
however, you should really have a think about the contract on the API, and enforce a certain return type from your API, and not just simply return the response from the SQL query. i.e. your API could possibly return an object like -
{ count: x }
where its up to your API to transform the result from the SQL query in a way that satisfies the contract, that way your React client is disconnected from your database layer and only cares about your API contract.
That way your client side becomes something like -
fetchData.data.count
which wouldn't break if the query where to be updated in some way etc.
I have read all sorts of variations of this on stackoverflow but I cannot seem to find a post that exactly explains what I'm trying to achieve, at the same time I believe this has to be a very common task during saving data.
So I need to save data to one collection and then read the _id from that doc and save it to a doc in a different collection. I have the following code and I can see the correct data with console.log but I don't see the data being saved to the database.
Appreciate if someone can guide me in the right direction.
Thank you!
router.post('/signup', async (req, res) => {
const { email, password, name, country } = req.body;
try {
const user = new User({ email, password });
await user.save((error, doc) => {
if (error) {
console.log(error);
} else {
const userProfile = new UserProfile({ userId: doc._id, name, country });
userProfile.save((error, doc) => {
if (error) {
console.log(error)
} else {
console.log(doc) // Can see this log with the correct data
}
});
}
});
const token = jwt.sign({userId: user._id}, 'MY_KEY');
res.send({ token });
} catch(error) {
return res.status(422).send(error.message)
}
})