'Array.prototype.map() expects a return value from arrow function array-callback-return
Don't really know why it is saying this but this is the code I believe it is talking about
setUpdate(text, key) {
const items = this.state.items;
items.map((item) => {
if (item.key === key) {
item.text = text;
}
});
this.setState({
items: items,
});
}
Solution 1:[1]
You have to use like below
setUpdate(text, key) {
// loop the existing state and find the key value
const nextItem = this.state.items.map((item) => {
if (item.key === key) {
item.text = text;
}
// return the modified item
return item;
});
// set the new object into state
this.setState({items: nextItem });
}
Solution 2:[2]
Issue
The Array.prototype.map
function maps a one-to-one relationship, the resultant array will be the same length as the original. The error is saying that you aren't explicitly returning a value for each element iterated.
You also don't save the resultant mapped array. The result of your code is iteration over the items
array and mutation with item.text = text;
. In React state and props are to be considered immutable, mutating them directly is very anti-pattern.
setUpdate(text, key){
const items = this.state.items; // <-- saved state reference
items.map(item=>{ // <-- missing result array save
if(item.key===key){
item.text= text; // <-- state mutation!
}
// <-- missing return value (the error)
})
this.setState({
items: items // <-- same reference to previous state!
})
}
Solution
You will want to shallow copy the array as well as any nested object that are being updated. Use a functional state update to correctly create the next state array from the state array from the previous state. The reason for this is that the next version of the items
necessarily depends on the previous array.
setUpdate(text, key) {
this.setState((prevState) => ({
items: prevState.items.map((item) =>
item.key === key ? { ...item, key: text } : item
)
}));
}
Solution 3:[3]
Wrote this answer without realising that React requires you to provide a new array.
You shouldn't be using map
just to find and update an item in an array! What's wrong with find
?
find
will stop on the first element that matches the condition.
setUpdate(text, key){
const items = this.state.items;
const item = items.find(i => i.key === key);
if (item) item.text = text;
this.setState({
items: items
});
}
Solution 4:[4]
The error states that add a return
keywork inside of map arrow function not just any HTML or compnent
Eg `
{props.meetups.map((meetup) => {
return (
<MeetupItem
key={meetup.id}
id={meetup.id}
image={meetup.image}
title={meetup.title}
address={meetup.address}
description={meetup.description}
/>
);
})}
</ul>
`
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | |
Solution 4 | jaskirat Singh |