Print element inside array [duplicate] - javascript

This question already has answers here:
When should I use a return statement in ES6 arrow functions
(6 answers)
Closed 2 years ago.
I have some problem to print elements inside array.
This is my Code
const mapStateToProps = state => {
console.log('antipasti', state.antipasti)
return { antipasti: state.antipasti };
};
const ConnectedList = ({ antipasti }) => (
<ul>
{
antipasti
.filter(antipasto => !!antipasto )
.map(antipasto => {
console.log('antipasto', antipasto);
<li>{antipasto.title}</li>
})
}
</ul>
);
const List = connect(mapStateToProps)(ConnectedList);
export default List;
What I would to obtain:
I would to print the element inside state.antipasti, I have used the filter to not consider the undefined or null elements.
This console.log('antipasto', antipasto); prints:
antipasto {title: "Prova"}title: "Prova"__proto__: Object
so I have thought to use antipasto.title to obtain the title, but nothing appears.
I have imported this page, in another parent page only with

{
antipasti
.filter(antipasto => !!antipasto )
.map(antipasto => {
console.log('antipasto', antipasto);
<li>{antipasto.title}</li>
})
}
When you do antipasto => { <li /> } like that, you're not actually RETURNING anything to your .map function. In general, the React structure looks more like this
{
antipasti
.filter(antipasto => !!antipasto )
.map(antipasto => (<li>{antipasto.title}</li>)
}
You may also be able to explicitly return inside the function, like Yury suggests in your comments, but that's not as common of a pattern and you'd only be doing it to support your console.log statement.

Related

How to map data correctly before subscription?

I have following function:
this.localStorage.getItem('user').subscribe(user => {
this.user = user;
this.authSrv.getOrders(this.user.einsender).pipe(map(orders => {
map(order => { order["etz"] = "23"; return order})
return orders;
})).subscribe(orders => {
this.orders = orders;
this.completeOrders = orders;
console.log(orders);
this.waitUntilContentLoaded = true;
})
})
The result without the map is:
[{id: 1, etz: "21"}]
With the map from above I try to enter the array, then the order and in the order I try to change the etz property but somehow nothing changes. Can someone look over?
I appreciate any help!
I see multiple issues here.
Try to avoid nested subscriptions. Instead you could use one of the RxJS higher order mapping operators like switchMap. You could find differences b/n different higher order mapping operators here and here.
To adjust each element of the array you need to use Array#map method in addition to the RxJS map operator.
You could use JS spread operator to adjust some of the properties of the object and retain other properties.
Try the following
this.localStorage.getItem('user').pipe(
switchMap(user => {
this.user = user;
return this.authSrv.getOrders(this.user.einsender).pipe(
map(orders => orders.map(order => ({...order, order['etz']: '23'})))
});
})
).subscribe(
orders => {
this.orders = orders;
this.completeOrders = orders;
console.log(orders);
this.waitUntilContentLoaded = true;
},
error => {
// good practice to handle HTTP errors
}
);
map is an operator that goes in a pipe like this:
someObs$.pipe(map(arg => { return 'something'}));
You've done this:
someObs$.pipe(map(arg => {
map(arg => { return 'something' }) // this line here does nothing
return arg;
}));
It doesn't make any sense to use map inside the function you've given to map

Assign options in destructure [duplicate]

This question already has an answer here:
How to return a spread operator in a map arrow function in one line [duplicate]
(1 answer)
Closed 2 years ago.
I've tried to rewrite the following code according to ES6. I keep getting ESLint warnings, and I've spent about 20 minutes on it so far, I'm not quite sure how to write it...
.then(result => {
const [categories, properties, placements] = result.map(r => r.data);
this.properties = properties.map(property => {
{
...property,
category: categories.find(c => c.id === property.category_id),
property: placements.filter(p => p.property_id === property.id),
}
});
});
The code above just doesn't parse at all, but depending on what I've tried it says I can't use return {} in an arrow function.
If I try to just modify the argument I get an error to no-param-reassign
I realized I can run eslint fix to see how it would be done:
this.properties = properties.map(property => ({
...property,
category: categories.find(c => c.id === property.category_id),
property: placements.filter(p => p.property_id === property.id),
}));

Expected to return a value at the end of arrow function in react

I get the warning in the title when compiling. I understand that it is about not handling some cases of if, but how can I filter before mapping in the correct way?
componentDidMount() {
this.props.UserReducer.user.employeeInfoList.map(role => {
if (role.employeeType) this.rolesOfUser.push(role.employeeType);
if (role.xdockId) this.xdockIdsOfUser.push(role.xdockId);
});
}
It is because you are misusing map which is used for mapping/transforming one array to another. Having a call to map without a return value indicates a problem, as you shouldn't be using it to just iterate over an array performing some action.
It looks like what you really wanted was a forEach call.
To filter an array use Array#filter. Also you can use Array#forEach for your case
componentDidMount() {
this.props.UserReducer.user.employeeInfoList.forEach(role => {
if (role.employeeType) this.rolesOfUser.push(role.employeeType);
if (role.xdockId) this.xdockIdsOfUser.push(role.xdockId);
});
}
Or
componentDidMount() {
const rolesOfUser = this.props.UserReducer.user.employeeInfoList.filter(role => {
return role.employeeType;
})
const xdockIdsOfUser = this.props.UserReducer.user.employeeInfoList.filter(role => {
return role.xdockId;
})
// Do smth with both arrays
}

Why reducer ignores first item in the array?

I have this function that is supposed to run each validator and then return the object that contains errors.
Everything seems to work fine, but the first validator in the array. It seems like reduce completely ignores it. No matter what validator I put there, it just goes right over to the second one.
Am I missing something obvious here?
export default values => (
[
validateFullName,
validateServicePresence,
validatePhoneField,
validateOrganizationName,
validateInn,
validateEmailField,
validateManagerEmail,
validateComment,
validateAgreement,
].reduce((currentErrors, validator) => {
const validationResult = validator(values);
return {
...currentErrors,
...validationResult,
};
})
);
If you don't provide an initial value to reduce, then it will use the first element of the array as the initial value, and skip calling your reducer with that element. So the very first time your reducer is called, currentErrors is validateFullName, and validator is validateServicePresence.
To fix this, just add an initial value:
export default values => (
[
validateFullName,
validateServicePresence,
validatePhoneField,
validateOrganizationName,
validateInn,
validateEmailField,
validateManagerEmail,
validateComment,
validateAgreement,
].reduce((currentErrors, validator) => {
const validationResult = validator(values);
return {
...currentErrors,
...validationResult,
};
}, {}) // <===================
);
See the initialValue section here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce#Parameters
By default Array.prototype.reduce uses the first element as the accumulator value if no starting value is provided. Passing the statring value for the accumulator explicitly will make sure your first element is also processed.
See the initialValue parameter on the MDN docs
export default values => (
[
validateFullName,
validateServicePresence,
validatePhoneField,
validateOrganizationName,
validateInn,
validateEmailField,
validateManagerEmail,
validateComment,
validateAgreement,
].reduce((currentErrors, validator) => {
const validationResult = validator(values);
return {
...currentErrors,
...validationResult,
};
}, {})
);

React - map over array object and pass to options prop in react-select [duplicate]

This question already has answers here:
Cannot access correct this inside an axios callback [duplicate]
(1 answer)
React this.setState is not a function
(16 answers)
Closed 4 years ago.
I'm trying to map over an array of objects and use the name key to pass it to the options prop in react-select. Can I just do this using regular JS? I'm trying to incorporate this example.
My mock data
mock.onGet("/dataschemas").reply(200, {
data: [
{
id: "2147483599",
selfUri: "/dataschemas/2147483599",
name: "Book Catalog"
},
{
id: "2147483600",
selfUri: "/dataschemas/2147483600",
name: "Business Articles"
},
{
id: "2147483602",
selfUri: "/dataschemas/2147483602",
name: "Phone Data"
}
]
});
In cDM I'm updating state with the response and storing it in schemas
componentDidMount() {
axios.get("/dataschemas").then(function(response) {
console.log(response.data.data);
this.setState({
schemas: response.data.data
});
console.log(this.state.schemas);
});
}
Then in my select component I'm setting the schemas to the options prop and mapping over that in the values prop
<Select
id="color"
options={this.state.schemas}
isMulti={false}
value={this.state.schemas.filter(
({ name }) => name === this.state.name
)}
getOptionLabel={({ name }) => name}
getOptionValue={({ id }) => id}
onChange={({ value }) => this.setState({ name: value })}
onBlur={this.handleBlur}
/>
I can't seem to get the right values in props, to display the dataschema names in the dropdown selection in my codesandbox example
More info on react-select docs pertaining to this issue
The <Select> component's value prop expect a single object/value. However in the following code:
this.state.schemas.filter(
({ name }) => name === this.state.name
)
Calling .filter on an array returns another array. So you're passing an array to value, not a single object. You just need to add a [0] to unwrap the array:
this.state.schemas.filter(
({ name }) => name === this.state.name
)[0]
Or use .find instead:
this.state.schemas.find(
({ name }) => name === this.state.name
)
here's a working codesandbox
it seems like the problem was that you were using function syntax instead of fat arrow syntax and as a result this was being bound incorrectly so this.setState was undefined
more info about the difference between function and fat arrow syntax here
How does this work? I like to think of it as fat arrow functions don’t
have their own or don’t change the context of ‘this’. They leave it
alone so that it stays the same as the context in which the function
was created.
For debugging future issues like this, I recommend starting off by looking at the javascript console errors -- the initial tip was an error there that this.setState was undefined
You are trying to access state from inside the response function scope.
change your componentDidMount to this:
async componentDidMount() {
const response = await axios.get("/dataschemas");
if (response.data && response.data.data) {
this.setState({ schemas: response.data.data });
}
}

Categories

Resources