Good use of refetch for ListView with graphql_flutter - graphql-flutter

This is my query
Query(
options: QueryOptions(
document: gql(query),
variables: {
'startIndex': startIndex,
'endIndex': startIndex + 50
},
fetchPolicy: FetchPolicy.cacheAndNetwork,
),
builder: (
QueryResult result, { VoidCallback refetch, FetchMore fetchMore }
)
{
if (result.data == null){
refetch();
print('data is null');
}
startIndex = repositories.length;
print(startIndex);
return ListView.builder();
everytime I reload the page, it is showing
result: null
when print(result);
Then I added refetch() if result is null. Now it is showing
Query is not refetch safe
I used graphql_flutter ^5.0.0

Related

FormatException (FormatException: Invalid date format)

It seems that my string is not a valid format to parse the DateTime i can't seem to understand where the culprit is.
This happen from time to time when the app initiate the data.
error code :
initListOfUsageValues() async {
if (favoriteBike != null) {
int periodWanted;
if (displayedUsageType == "year") {
periodWanted = displayedYear;
} else if (displayedUsageType == "month") {
periodWanted = displayedMonth;
} else {
periodWanted = displayedWeek;
}
List<int> list = await APIBike().getUsageData(
jwt: _user!.jwt,
bikeId: favoriteBike!.id,
year: displayedYear,
duration: displayedUsageType,
periodWanted: periodWanted,
);
//The received list is in seconds so we need to convert it in minute
list = convertSecondsToMinute(list);
setState(() {
listOfUsageValues = list;
});
} else {
print("favoriteBike null in initListOfUsageValues");
//check if the alertdialog saying that there is no bike linked to this account yet has been displayed already or no
final storage = new FlutterSecureStorage();
String lastNoBikeAlertShowUp =
await storage.read(key: "last_no-bike-alert_show-up") ?? "";
//If there is more than 60 minutes since last show up, we show the alertdialog saying that there is no bike linked to this account yet, else we don't
DateTime lastNoBikeAlertShowUpDateTime =
DateTime.parse(lastNoBikeAlertShowUp);
var now = new DateTime.now();
int timeInMinuteSinceLastAlertShowUp =
now.difference(lastNoBikeAlertShowUpDateTime).inMinutes;
if (timeInMinuteSinceLastAlertShowUp > 60) {
await storage.write(
key: "last_no-bike-alert_show-up", value: now.toString());
showDialog(
context: context,
builder: (BuildContext context) {
return noBikeYetAlertDialog(context);
});
}
}
}
The error is trigered in this line :
DateTime lastNoBikeAlertShowUpDateTime =
DateTime.parse(lastNoBikeAlertShowUp);
lastNoBikeAlertShowUp is empty string. Because you see break on trow FormatException inside of date_time.dart
// set default date or check if it is not empty
String lastNoBikeAlertShowUp = await storage.read(key: "last_no-bike-alert_show-up") ?? "";
if(lastNoBikeAlertShowUp.isNotEmpty){
}

Filtering a list according to a parameter in Angular / IONIC 4

I have this function that returns a list of pokemons from a JSON URL of pokeapi.
I need to filter this function so that it shows those of a certain type that I bring with the variable dataPoke.
The variable is returned with the correct value, but I don't know how to give it filtered output and that it only shows the pokemons of the dataPoke type.
I get data from https://pokeapi.co/api/v2/pokemon https://pokeapi.co/api/v2/pokemon/3
listadoPokemonFiltrado(salida = 0,dataPoke) {
console.log("datos recibidos: ", dataPoke);
return this.http.get(`${this.baseUrl}/pokemon?salida=${salida}`)
.pipe(
map(result => { return result['results'];}),
map(pokemon => {
return pokemon.map((arreglo, index) => {
arreglo.image = this.obtenerImagen(salida + index + 1);
arreglo.pokeIndex = salida + index + 1;
arreglo.type = this.obtenerTypo(dataPoke);
arreglo.pokeIndex = arreglo.type;
return arreglo;
});
})
);
}
obtenerImagen(index) {
return `${this.imageUrl}${index}.png`;
}
obtenerTypo(index) {
return `${this.baseUrlTypes}/${index}`;
}
Reading code not in English is certainly a challenge, but I assume that what you're looking for is filtering your array?
listadoPokemonFiltrado(salida = 0, dataPoke) {
console.log('datos recibidos: ', dataPoke);
return this.http.get(`${this.baseUrl}/pokemon?salida=${salida}`).pipe(
map(result => result['results']),
map(pokemons => {
return pokemons
.filter(pokemon => pokemon.type === dataPoke)
.map((arreglo, index) => {
arreglo.image = this.obtenerImagen(salida + index + 1);
arreglo.pokeIndex = salida + index + 1;
arreglo.type = this.obtenerTypo(dataPoke);
arreglo.pokeIndex = arreglo.type;
return arreglo;
});
})
);
}
obtenerImagen(index) {
return `${this.imageUrl}${index}.png`;
}
obtenerTypo(index) {
return `${this.baseUrlTypes}/${index}`;
}
I have added .filter(pokemon => pokemon.type === dataPoke) to filter results array.

change value from of a specific item on button click

As I asked yesterday in my first post, I have a json file that looks like this:
groups:{[
{
title:Animal
shown:false
data:[{....}]
}
........
.....
]}
I want to change the shown value on a button click. The closest thing I found to my problem was this part of code:
newState = this.state.groups.map((val,i) => {
if(index === i){
return { ...val, shown: false};
}
return val;
})
this.setState({
groups: newState,
})
However, it doesn't seem to work, logging on console doesn't show any differences before and after the button press. I'm rather new to this so do you mind to help me understand what i did bad?
edit: I tried changing from index to a simple number to see if that was the problem, but still the same problem.
A JSON object is collection of Key Value pairs. i.e.
let FullName = {
firstName: "Stack",
lastName: "OverFlow"
}
In FullName Object Keys are firstName and lastName and corresponding values are "Stack" and "Overflow".
The groups Object that you have defined is missing the key Property.
Coming to Your problem:
Case1: If groups Object is an Array of Objects then:
var groups = [
{
title: 'Animal',
shown: false,
data: [{}]
},
{
title: 'Birds',
shown: false,
data: [{}]
}
]
/* Upadate By Index value */
/*
var index = 1;
let updatedGroup = groups.map((val,i) => {
if(index === i){
return { ...val, shown: true};
}
return val;
})
*/
/* Upadate By title */
/* let title = "Animal";
let updatedGroup = groups.map((val,i) => {
if(val.title === title){
return { ...val, shown: true};
}
return val;
}) */
// To toggle the shown Value Each Time
let title = "Animal";
let updatedGroup = groups.map((val,i) => {
if(val.title === title){
return { ...val, shown: !val.shown};
}
return val;
})
console.log("updatedGroup", updatedGroup);
Case2: If groups Object is Object of Objects then
var groups = {
group1: {
title: 'Animal',
shown: false,
data: [{}]
},
group2: {
title: 'Birds',
shown: false,
data: [{}]
}
}
let index = 1;
let updatedGroup = Object.values(groups).map((val, i)=>{
if(index === i){
return { ...val, shown: true};
}
return val;
})
console.log("updatedGroup",updatedGroup)

NodeJS mysql if null or empty

I have code, which should execute if the table is not in mysql or "NULL" or empty.
mysqlConnection.query('SELECT `something` FROM `here` WHERE `dog` = \'' +info+ '\'', function(err, row, fields) {
if(err) {
console.log('Error1');
return;
}
else if (!row.length) {
console.log('Error2');
return;
}
else if (row[0].something == 'NULL' || row[0].something == '') {
console.log('Error3');
return;
}
console.log('Works');
});
So the thing is, if "something" is not in mysql, console shows Error2, but if "something" is in mysql, but if its NULL, console shows Works, so whats the problem? Im checking if something is NULL, but it wont show Error3. If table is empty, it shows Error3. Thanks for help.
I would try something like this:
mysqlConnection.query('SELECT `something` FROM `here` WHERE `dog` = ?', [info] function(err, row, fields) {
if(err) {
return console.log('Error1');
} else if (!row.length) {
return console.log('Error2');
} else if (!row[0].something) {
return console.log('Error3');
}
console.log('Works');
});
It's using a "falsy" check for row[0].something which will return false if the value is undefined, null or an empty string. It also fixes the injection attack vector that t.niese mentioned.
I am aware that I am 5 years and 9 months late, but for those of you struggling with this,
here's a solution. The table's value when empty is not NULL. I was having a similar problem in which I wanted to reset AUTO_INCREMENT to 1 when the table is empty. To detect when it's empty, we have to see if it has any element with the index 0. If it has an element, it would return something like: RowDataPacket { // data }. If it doesn't, it would return undefined. See where I'm going with this? Just add a conditional to see if the result[0] is undefined or not. Want some code to better understand it? Sure! Here it is:
db.query("SELECT * FROM tablename", (err, result) => {
if (err) throw err;
else {
// If the first element does not exist
if (result[0] == undefined) {
db.query("yourquery", (err) => {
if (err) throw err;
});
} else {
res.send(result);
}
}
});
If you think in a scenario when you receive an Array<any> when you run a SQL like select name from employee there are three concerns you should have:
If your statement did return something
If the property you are looking for exist
If the content of the property is null and you are expecting a null
As these concerns will occur hundreds of time, I use the following approach (in TypeScript):
let ret: Array<any> = connection.query('select name from employee',...);
for (let r of ret) {
name = getValueColumn(r,'name','This will be thrown if content is null');
};
export function getValueColumn(obj: any, fieldName: string, messageIfNull: string = null): any {
fieldName = fieldName.toLocaleLowerCase();
if (!obj) {
throw new CustomError(errorCodes.connection.rowNull, 'Linha nula e sem campos');
} else if (!obj.hasOwnProperty(fieldName)) {
throw new CustomError(errorCodes.connection.fieldDoesNotExist, 'Campo não existe -> ' + fieldName);
} else {
if (!obj[fieldName]) {
if (messageIfNull) {
throw new CustomError(errorCodes.connection.fieldWithNullValue, messageIfNull + '\n' + fieldName +
' com valores nulos ou campo invalido\n' + obj);
};
return null;
};
return obj[fieldName];
};
};
If you were to check the results with just if (!ret) {...}, it would be always false as an empty array is not null. So you would have to check if(!ret[0]) {..}
So all three concerns are handled and you don't need to be worried every time you want to parse the query.

Define json specific field is declared or not

I have Asp.Net Mvc4 application. In one Action method I have conditional process that return different json result as follows:
if(true)
{
return Json(new { count = cartItm.ProductCount, total = cartItm.TotalAmount });
}
else
{
return Json(new
{
thumb = item.ThumbnailPhoto,
productName = item.Name,
itemCount = cartItem.ProductCount,
itemTotal = cartItem.TotalAmount,
productTotal = cart.TotalAmount,
productCount = cart.CartItems.Sum(items=>items.ProductCount)
});
}
In jquery click event I can't define which json is returned. I write if condition as follows but get wrong result.
success: function (data) {
if (data.thumb != null) {//some operations }
else{//some operations }
Perhaps it is very easy problem, but I am new with json. Please help me.
thanks for reply
Check for "undefined" instead
success: function (data) {
if (typeof data.thumb !== "undefined") {//some operations }
else{//some operations }
Because item.ThumbnailPhoto on your server may be null. If this is the case, your check will fail.
Try this,
success: function (data) {
if (data && data.thumb) {//some operations }
else{//some operations }
}
The problem might be because you don't have data.thumbs in your first json, in your Action,
if(true)
{
return Json(new { flag = 1, count = cartItm.ProductCount, total = cartItm.TotalAmount });
}
else
{
return Json(new
{
flag = 2,
thumb = item.ThumbnailPhoto,
productName = item.Name,
itemCount = cartItem.ProductCount,
itemTotal = cartItem.TotalAmount,
productTotal = cart.TotalAmount,
productCount = cart.CartItems.Sum(items=>items.ProductCount)
});
}
in your view :
success: function (data) {
if (data.flag == 1) {//some operations }
elseif (data.flag == 2) {//some operations }
didnt check the code, but this must work.