Multiple map on array React Native - arrays

Use multiple Map on array. I get error:
SyntaxError: C:\Users\Laptop15\Desktop\React Native\src\screens\Question.js: Unexpected token, expected "," (59:7)
I use function that: {PytaniePush(quizDane.quest1)}
function PytaniePush(myID) {
if(quizDane && quizDane.quest1 && myID){
myID.map((item, key)=>(
myID[key].map((item2, key2)=>(
return ({RadioPush(myID[key].item2)});
));
));
}
}
I want to console log with all elements in array and object:
quest1->array[Object(A,B), Object(A,B)]
Data look: that
I want to get:
A in 0 is ...
B in 0 is ...
A in 1 is ...
B in 1 is ...

You have an syntax error in your code. Here is right code.
function PytaniePush(myID) {
if (quizDane && quizDane.quest1 && myID) {
myID.map((item, key) =>
myID[key].map((item2, key2) => {
return RadioPush(myID[key].item2);
})
);
}
}
Next time when you will have a syntax error try to use Prettier to find error and improve format of your code.

There are some syntax errors in your code. Try this one.
function PytaniePush(myID) {
if(quizDane && quizDane.quest1 && myID){
myID.map((item, key) => myID[key].map((item2, key2) => {
return RadioPush(myID[key].item2);
} ));
}
}
Try to use an ES6 aware IDE. That way you will not stumble upon this kind of issues.

Related

React Cannot read properties of undefined (reading ‘map’)

I'm writing code that stores data about the walks that person do during the week.
Code: https://stackblitz.com/edit/react-wbn3ms?file=src%2FStepsForm.js
dataList works well in console but in browser there is an error:
Uncaught TypeError: Cannot read properties of undefined (reading ‘map’)
at StepsForm (StepsForm.js:84:1)
Also, when I add date it's double date.
It should work this way: https://www.loom.com/share/0159984de8474c7ab090361b3f6b68d4
Could you please help me, what do I do wrong?
setList((prevList) => {
if (index === -1) {
prevList.push(newData);
prevList
.sort((a, b) => {
return a.id - b.id;
})
.reverse();
} else {
prevList[index].distance = String(
prevList[index].distance * 1 + newData.distance * 1
);
}
return [ ...prevList ];
});
add return [...prevList] at the end you were not returning it and it was undefined and was not a array so map error

Nextjs 'endsWith' polyfill problem on edge and ie11

My site breaks and fails running because of the Object doesn't support property or method 'endsWith' error. I've tried polyfilling it with import 'core-js/features/string/ends-with' or
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length
}
return this.substring(this_len - search.length, this_len) === search
}
}
I've done that in my custom _app file but it still fails in edge and ie11. What am I missing?
Edit: Judging by the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith#Browser_compatibility endsWith should be supported in Edge
Try to add this to your code.
String.prototype.endsWith = function(pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};

React : Pushing result of map() to an array

Hello I am trying to map through an array of objects and push them to a new array.
My ISSUE : only the last item of the object is being pushed to the new array
I believe this has to do with React life cycle methods but I don't know where I should I loop and push the values to the array to get the full list
//My object in an array named states
var states = [{"_id":"Virginia","name":"Virginia","abbreviation":"VN","__v":0},{"_id":"North Carolina","name":"North Carolina","abbreviation":"NC","__v":0},{"_id":"California","name":"California","abbreviation":"CA","__v":0}];
export function StateSelect()
{
**EDIT 1**
const options = [];
function getStates()
{
//This is how I am looping through it and adding to an array
{ states.length > 0 &&
states.map(item =>
(
console.log(`ITEM: ${JSON.stringify(item)}`),
options.push([{ value: `${item.name}`, label: `${item.name}`}])
))
}
}
return( {getStates()}: );
}
Thank you
It looks like your getStates() might not even be returning anything... but assuming it is, I believe you should be able to accomplish this using a forEach() fn in order to push values into your options array... Try adding the following into your map:
states.map((item) => {
console.log(`ITEM: ${JSON.stringify(item)}`);
let processed = 0;
item.forEach((i) => {
options.push([{ value: `${i.name}`, label: `${i.name}`}]);
processed++;
if(processed === item.length) {
// callback fn, or return
}
}
.map usually used to return another result, you could just use .forEach
In fact, you don't really need to declare options at all, just use .map on state to return the result would be fine.
return states.length > 0 && states.map(({ name }) => {
return { value: name, label: name };
});

typescript filter array on 2 parameters

In order to filter an array on possibly 2 parameters I have written the following code:
filterStudies(searchString?: string) {
if (searchString && !this.selectedModalityType) {
this.studies = this.fullStudyList.filter(function (study) {
return (study.Code.toUpperCase().includes(searchString.toUpperCase())) ||
(study.Description.toUpperCase().includes(searchString.toUpperCase()));
})
} else if (!searchString && this.selectedModalityType) {
console.log(this.selectedModalityType)
this.studies = this.fullStudyList.filter(function (study) {
return (study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
})
} else if (searchString && this.selectedModalityType) {
this.studies = this.fullStudyList.filter(function (study) {
return (study.Code.toUpperCase().includes(searchString.toUpperCase())) ||
(study.Description.toUpperCase().includes(searchString.toUpperCase())) &&
(study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
})
}
}
filterStudies(searchString?: string) is called when typing in a textbox that.
The other way of filtering could be by selecting a value from a dropdown box. Achieved by this code:
handleSelection(value:any){
this.selectedModalityType = value;
console.log(value)
this.filterStudies()
}
All works fine until this code is hit:
this.studies = this.fullStudyList.filter(function (study) {
return (study.ModalityType.Code.toUpperCase() === this.selectedModalityType.toUpperCase())
})
Error message : ERROR TypeError: Cannot read property 'selectedModalityType' of undefined, I see it is actually logged in the line before.
What am I missing??
Thanks,
In your funtcion, this is not the same this as the line before.
This will work:
let self = this;
this.studies = this.fullStudyList.filter(function (study) {
return (study.ModalityType.Code.toUpperCase() === self.selectedModalityType.toUpperCase())
})
You can read this to learn more: https://github.com/Microsoft/TypeScript/wiki/%27this%27-in-TypeScript
The this keyword in JavaScript (and thus TypeScript) behaves differently than it does in many other languages. This can be very surprising, especially for users of other languages that have certain intuitions about how this should work.
(...)
Typical symptoms of a lost this context include:
A class field (this.foo) is undefined when some other value was expected

Cannot read property 'toJS' of undefined

I have two arrays. But when one of them is null it gives the following error:
Cannot read property 'toJS' of undefined in that line
Here's the relevant call that triggers the error: {groupsGuney.toJS()}
Here's my declaration of the variables let groupsGuney, groupsKuzey;
And finally here are my two arrays. But when one of them is null it gives the error:
...
if (muso == 1) {
groupsGuney = this.props.groups
.groupBy((group, idx) => idx % maxRows)
.map((ggs, idx) => {
return this.renderGroups(ggs, idx);
}).toList().flatten(true);
}
if (muso == 2) {
groupsKuzey = this.props.groups
.groupBy((group, idx) => idx % maxRows)
.map((ggs, idx) => {
return this.renderGroups(ggs, idx);
}).toList().flatten(true);
}
var result = (
<div>
<div className={classSelector + ' discard-mini-box-area'} >
{ groupsGuney.toJS() }
</div>
<div className={classSelector + ' discard-mini-box-area'} >
{ groupsKuzey.toJS() }
</div>
</div>
);
return result;
}
}
export default DiscardMiniBoxArea;
Instead of doing:
<div>
<div className={classSelector + ' discard-mini-box-area'} >
{groupsGuney.toJS()}
</div>
....
you should do:
<div>
<div className={classSelector + ' discard-mini-box-area'} >
{groupsGuney && groupsGuney.toJS()}
</div>
....
Before calling a function on your object, you need to make sure it's there. If you're uncertain about your object having the function at all times, you will need an additional check, that makes sure toJS is there and that it's a valid function.
If that's the case, update what's inside your container to:
{groupsGuney && typeof groupsGuney.toJS === 'function' && groupsGuney.toJS()}
However, ideally, you would not render at all this specific group if what you would like to render is not there. You should move these checks to before you render your component.
My motivation here is mostly that my call .get of undefined poops itself really hard, and initializing properly all over the place helps, but doesn't catch all edge cases. I just want the data or undefined without any breakage. Specific type checking causes me to do more work later if I want it to make changes.
This looser version solves many more edge cases(most if not all extend type Iterable which has .get, and all data is eventually gotten) than a specific type check does(which usually only saves you when you try to update on the wrong type etc).
/* getValid: Checks for valid ImmutableJS type Iterable
returns valid Iterable, valid Iterable child data, or undefined
Iterable.isIterable(maybeIterable) && maybeIterable.get(['data', key], Map()), becomes
getValid(maybeIterable, ['data', key], Map())
But wait! There's more! As a result:
getValid(maybeIterable) returns the maybeIterable or undefined
and we can still say getValid(maybeIterable, null, Map()) returns the maybeIterable or Map() */
export const getValid = (maybeIterable, path, getInstead) =>
Iterable.isIterable(maybeIterable) && path
? ((typeof path === 'object' && maybeIterable.getIn(path, getInstead)) || maybeIterable.get(path, getInstead))
: Iterable.isIterable(maybeIterable) && maybeIterable || getInstead;
//Here is an untested version that a friend requested. It is slightly easier to grok.
export const getValid = (maybeIterable, path, getInstead) => {
if(valid(maybeIterable)) { // Check if it is valid
if(path) { // Check if it has a key
if(typeof path === 'object') { // Check if it is an 'array'
return maybeIterable.getIn(path, getInstead) // Get your stuff
} else {
maybeIterable.get(path, getInstead) // Get your stuff
}
} else {
return maybeIterable || getInstead; // No key? just return the valid Iterable
}
} else {
return undefined; // Not valid, return undefined, perhaps should return false here
}
}
Just give me what I am asking for or tell me no. Don't explode. I believe underscore does something similar also.

Resources