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);
}
Related
i am using Redux-Toolkit-Query in Reactjs Project, I have Number of end points. For Each Endpoint i have to add one common parameter with body , i tried below snippet on QueryStarted adding that Language parameter, but i am repeating this code for each enpoint and sometimes its not working.
updatePassword: builder.mutation({
query: (body) => ({
url: URL.UPDATE_PASSWORD,
method: "POST",
body: body,
responseHandler: (response) => response.json(),
validateStatus: (response, result) =>
response.status === 200 && result.success === 1,
}),
transformResponse: (response) => {
return response;
},
async onQueryStarted(body, { dispatch, queryFulfilled, getState }) {
const language = await UTILS?.asyncLocalStorage.getLanguage(); //Here How to add this with body
body.language = language;
const { history } = body;
try {
dispatch(LoaderAction.setLoading(true));
const { data } = await queryFulfilled;
if (data) {
UTILS.handleSuccesNotification(
data?.message ?? "Password updated sucessfully"
);
history.goBack();
}
} catch (err) {}
dispatch(LoaderAction.setLoading(false));
},
}),
I've an api created with RTK Query, and I have a create endpoint that pessimistically updates other queries:
create: builder.mutation<
{ id: string },
Req
>({
query: (req) => ({
url: "",
method: "POST",
body: req,
}),
async onQueryStarted(req, { dispatch, queryFulfilled }) {
try {
const {
data: { id },
} = await queryFulfilled;
dispatch(
apiSvc.util.updateQueryData(
"getFoos",
{ specialId: req.specialId },
(draft) => {
draft.unshift({
...req,
id
});
}
)
);
dispatch(
apiSvc.util.updateQueryData(
"getSingleFoo",
{ specialId: req.specialId, otherSpecialId: req.otherSpecialId },
(draft) => {
Object.assign(draft, {
...req,
id
});
}
)
);
} catch (e) {
console.error(e);
}
},
}),
But updating the getSingleFoo doesn't update the cache value correctly, only getFoos is updated.
Is it possible to do this? If so how?
If anyone wonders here, I asked in the repo.
As you can in the react (clint-side) code , i am trying increase/decrese of Quantity in database and UI.
in this code i am sucessfully show quantity in console . but i don't show it my UI and database . Now what should i do ?
Server side (react)
const { register, handleSubmit } = useForm();
const onSubmit = (data, event) => {
const url = https://nameless-dusk 43671.herokuapp.com/products/${productsId}
fetch(url, {
method: "PUT",
headers: {
'content-type': "application/json"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(result => {
console.log(result)
event.target.reset()
}
)
}
update item on clint side
app.put('/products/:id', async (req, res) => {
const id = req.params.id;
const updateUser = req.body;
const filter = { _id: ObjectId(id) }
const options = { upsert: true };
const updateDoc = {
$set: {
name: updateUser.name,
email: updateUser.email,
}
}
const result = await
ProductCollection.updateOne(filter, updateDoc,
options)
res.send(result)
})
I need a way to make a request with method Post passing a body but I didnt find a way to do it. The documentation: https://docs.expo.io/versions/latest/sdk/filesystem/ only show the GET method, I need a way to make a post request passing the body.
FileSystem.downloadAsync(${baseUrl}/v1/paycheck/pdf, FileSystem.documentDirectory + ‘file.pdf’,
{
headers: {
‘Authorization’: localToken
},
httpMethod: ‘POST’,
body: {
type: 'monthy',
year: '2021',
month: 2,
employer: {
name: "Pink",
}
}
}
)
.then(({uri}) => {
Sharing.shareAsync(uri, {dialogTitle: 'Salvar ou Compartilhar'})
})
.catch(error => {
console.error(error);
});
}
As far as I understand your problem
My Approach for Downloading and Sharing the PDF would be
Writing these two functions
// Execute this function when you to share the file...
const GetPDF = async () => {
try {
const response = await fetch(`${baseUrl}/v1/paycheck/pdf`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: "localToken",
},
body: JSON.stringify({
type: "monthy",
year: "2021",
month: 2,
employer: {
name: "Pink",
},
}),
});
const content = await response.json();
DownloadThenShare(content); // Some URI
} catch (error) {
console.error(error);
}
};
Now DownloadAndShare function
// This function will execute after Download has been completed successfully
const DownloadThenShare = async (uri) => {
const downloadInstance = FileSystem.createDownloadResumable(
uri,
FileSystem.documentDirectory + "file.pdf"
);
const result = await FileSystem.downloadInstance.downloadAsync();
if (result.status === 200) {
Sharing.shareAsync(result.uri, { dialogTitle: "Salvar ou Compartilhar" });
} else {
console.log("Failed to Download");
}
};
I finally managed to make it work using axios e FileReader();
const response = await axios.post(`${baseUrl}/v1/paycheck/pdf`, data, {responseType: 'blob'});
const fr = new FileReader();
fr.onload = async () => {
const fileUri = `${FileSystem.documentDirectory}/document.pdf`;
const result = await FileSystem.writeAsStringAsync(fileUri, fr.result.split(',')[1], {encoding: FileSystem.EncodingType.Base64});
saveFile(fileUri);
};
fr.readAsDataURL(response.data);
I don't know what is going on. When i try to send request to the backend to add follower(my route bellow), I get server tiemout error instead of sucess, but in my database the follower is added correctly(and removed), buuuut not always. Sometimes it saves 3 times the same result(follower to db), or sometimes doesn't delete the follower.
And the problem is that i have no idea what's is going on.
In my console i have this error sometimes i see this:
[HPM] Error occurred while trying to proxy request /api/users/user/follow from 127.0.0.1:8080 to http://[::1]:1648 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
setFollower route:
const setFollowing = async (req, res, next) => {
try {
const userId = req.body.userId;
const followId = req.body.followId;
await User.findByIdAndUpdate(
userId,
{
$push: {
following: followId,
},
},
);
next();
} catch (err) {
res.status(400).json({
error: err,
});
}
};
const setFollower = async (req: Request, res: Response) => {
try {
const followId = req.body.followId;
const userId = req.body.userId;
const result = await User.findByIdAndUpdate(
followId,
{
$push: {
followers: userId,
},
},
{ new: true },
)
.populate('following', '_id name')
.populate('followers', '_id name')
const followerResult = { ...result._doc };
const { photo, salt, passwordHash, ...rest } = followerResult;
return res.status({ ...rest });
} catch (err) {
res.status(400).json({
error: err,
});
}
};
router.put(
'/user/follow',
isUserSignIn,
setFollowing,
setFollower,
);
sending request on button click
try {
setLoading(true);
const response = await fetch('/api/users/user/follow', {
body: JSON.stringify({
followId: params.userId,
userId: loggedInUser._id,
}),
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
method: 'PUT',
});
const data = await response.json();
setLoading(false);
setFollowing(true);
} catch (err) {
if (err.message) {
setServerError(err.message);
} else {
setServerError(JSON.stringify(err));
}
}
my repo: https://github.com/bartek-fecko/fullstackapp
for my assumption, you're using express, given the logs you have in your question. The
key is to set the timeout property on server (the following sets the timeout to one
second, use whatever value you want):
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
server.timeout = 1000;