How fetch data between two dates with axios ?
This is what I've tried so far:
const res = axios.get("/activities", {
params: {
date: {
gte: startDate,
lte: endDate
},
user: id
}
});
Ok so I read the documentation of strapi and I have the issue :
const res = axios.get("/activities", {
params: {
date_lt: startDate,
user: id
}
});
It's not precise to add _lt or _gt at the end of the value I want to check
Related
so I am trying to 'chain' togther multiple queries that are somewhat dependent on each other, using RTK Query and I'm not getting very far...
APIS
import { baseApi } from '#/lib/rtkQuery/baseApi';
export const personContactApi = baseApi
.enhanceEndpoints({ addTagTypes: ['mail_packs'] })
.injectEndpoints({
endpoints: (build) => ({
createList: build.mutation({
query: (body) => {
return {
url: `/person/list/`,
method: 'POST',
body,
};
},
}),
addPersonsToList: build.mutation({
query: ({ ListId, personArray }) => {
return {
url: `/person/list/${ListId}/add-persons/`,
method: 'POST',
body: { persons: personArray },
};
},
}),
sendList: build.mutation({
query: ({ ListId }) => {
return {
url: `/person/list/${ListId}/submit/`,
method: 'POST',
};
},
}),
}),
});
export const { useCreateListMutation, useAddpersonsToListMutation, useSendListMutation } =
personContactApi;
Query functions
const [createList, { data: listResponseObject, isSuccess: createListSuccess, isError: createListError }] = useCreateListMutation();
const [addPersonsToListMutation, { isSuccess: addPersonsToListSuccess, isError: addPersonsToListError }] = useAddPersonsToListMutation();
const [sendList, { isSuccess: sendListSuccess, isError: sendListError }] = useSendListMutation();
useEffect
useEffect(() => {
// When list successfully created, add persons to list
if (createListSuccess) {
addPersonsToListMutation({
ListId: listResponseObject?.id,
personsArray: selectedPersons,
});
}
}, [
addPersonsToListMutation,
createListSuccess,
listResponseObject,
selectedPersons,
]);
useEffect(() => {
// When persons have been successfully added to mailing list, send mailing list
if (addPersonsToListSuccess) {
sendList({
listId: listResponseObject?.id,
});
}
}, [
addPersonsToListSuccess,
listResponseObject,
sendList,
]);
These are the 3 queries / mutations and they need to go in order, once the create query is success we fire the add, once that is a success we fire the send
The add and send queries are also dependent on an id returned in the response from the createList query, and the add query required an array of ids representing the person objects being added to the list
I've hacked togther a solution using multiple useEffects but it is very brittle and obviously not the ideal way to handle this situation, any one have a better way I'm all ears.
One way of solving this would be to follow one of their official suggestions:
If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().
In your example, the code would be something like this
createList(input_object_goes_here)
.unwrap()
.then(createListResponse => {
addPersonsToListMutation(createListResponse.values_you_need)
.unwrap()
.then(addPersonsResponse => sendList({ listId: addPersonsResponse.id }))
})
Hope I got the syntax right, but you should get the idea.
Source: https://redux-toolkit.js.org/rtk-query/usage/error-handling
I am currently creating an animal shelter web app using mern and i have trouble grouping data by date month. so i have this schema for the rescued date:
const animalSchema = new mongoose.Schema({
date_rescued: {
type: Date,
default: Date.now,
},
})
module.exports = mongoose.model('Animal', animalSchema);
And here on my animal controller backend this is my query for fetching the datas:
exports.getRescuedChart = async(req,res,next) => {
const rescuedanimals = await Animal.find({}).select(['date_rescued']);
res.status(200).json({
success:true,
rescuedanimals,
})
}
the data that this function is returning to the state is this:
what i want to have is group them by data and count how many object has the same date.
rescuedanimals =[
{
date_rescued: "April",
animal_count: 8
}
]
so yeah i just learn how to do it myself so here's what i did.
first is that i installed dataeformat library: 'npm install dateformat'
i import it on my project: import dateFormat from 'dateformat';
what i did first is to change the date format and reduce duplicate dates.
const groups = rescuedanimals.reduce(
(groups, rescued_animal) => {
const date = dateFormat(rescued_animal.date_rescued[0], "mmmm")
if (!groups[date]) {
groups[date]=[]
}
groups[date].push(rescued_animal);
return groups;
}, {}
)
after that i created a new function to put this on an arraay and also to get the legnth of the objects that are in that date.
const groupArrays = Object.keys(groups).map((date) => {
return {
date,
games: groups[date].length
};
});
thanks to Austin Greco: https://stackoverflow.com/a/46802505/12398637
I am trying to fulfill the getStaticPaths of NextJS that demand records to be formatted as:
Which demand the format like so:
[
{
params: {
id: recordId
}
}
]
I can achieve this result with:
const res = await myModel.findAll({
raw: true,
attributes: ['id'],
});
const fixedFormat = res.map(singleRes => {
return {
params: {
id: singleRes.id,
},
};
});
But I was wondering if there's a way that doesn't involve calling map() on such a big array.
I am trying to insert data from my backend to MongoDb. For example if I want to insert "2021-06-03" I will get "2021-06-02T21:00:00.000+00:00".
Model :
const organizerSchema = new mongoose.Schema({
description: { type: String, required: true },
duration: { type: Number },
location: { type: String },
date: { type: Date, default: Date.now },
And route :
const { description } = req.body;
const { date } = req.body;
const { location } = req.body;
const { duration } = req.body;
const newAdd = new Add({
description,
date,
location,
duration,
});
try
date: { type: Date, default: new Date() },
Why dont you try and saving it as a unix using moment ( moment().unix() )? This is a number and you should be able to easily convert it back to date.
Otherwise use moment to convert it to the proper timezone
moment(date).utcOffset('+0300').format(format)
I'm getting a warning:
Cache data may be lost when replacing the parts field of a Query object.
To address this problem (which is not a bug in Apollo Client), define a custom merge function for the Query.parts field, so InMemoryCache can safely merge these objects:
existing: [{"__ref":"Part:53"},{"__ref":"Part:55"},{"__ref":"Part:56"},{"__ref":"Part:57"},{"__ref":"Part:58"}]
incoming: [{"__ref":"Part:53"},{"__ref":"Part:55"},{"__ref":"Part:56"},{"__ref":"Part:57"}]
Now here is my Part type:
type Part {
id: ID!
created_at: DateTime!
updated_at: DateTime!
partName: String
partDescription: String
partQuantity: Long
usePercentage: Boolean
partPercentage: Float
type: String
published_at: DateTime
products(sort: String, limit: Int, start: Int, where: JSON): [Product]
partImage(sort: String, limit: Int, start: Int, where: JSON): [UploadFile]
stockevents(sort: String, limit: Int, start: Int, where: JSON): [Stockevent]
}
This warning triggers after I remove one part using mutation to delete a single part. Here it is:
const [partDelete] = useMutation(DELETE_PART, {
update(cache, { data }) {
const newData = Object.values(data)
const refresh = newData.map(name => name.part)
const refined = refresh.map(item => item.id)
cache.evict({
id: cache.identify({
id: refined.id
})
})
cache.writeQuery({
query: GET_PARTS
})
},
refetchQueries: [
{ query: GET_PARTS }
]
})
I am passing payload in a separate function and everything works but I keep getting this cache warning so I want to deal with it now.
I've went with updating InMemoryCache in my index.js but it still doesn't work:
export const client = new ApolloClient({
link,
cache: new InMemoryCache({
typePolicies: {
Part: {
merge(existing = [], incoming = []) {
return [...existing, ...incoming];
}
}
}
})
});
I've also tried to return only ...incoming but nothing different happens.
Thanks in advance, cheers!
The issue was in the structure of InMemoryCache config. After I changed it to this it worked:
export const client = new ApolloClient({
link,
cache: new InMemoryCache({
typePolicies: {
Query: {
Part: {
parts: {
fields: {
merge(existing, incoming) {
return incoming;
}
}
}
}
}
}
})
});
I have also removed update option from the mutation that includes evict and modify.
when you see this warning:
To address this problem (which is not a bug in Apollo Client), define a custom merge function for the Query.your_query_name field, so InMemoryCache can safely merge these objects:
try this for shorten:
const client = new ApolloClient({
uri: "your_API_link",
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
your_Query_Name: {
merge: (existing = [], incoming) => {
return incoming;
},
},
},
},
},
}),
});