Reputation:
I am using eslint and getting this error.
Expected to return a value in arrow function
The error is showing on the third line of the code.
useEffect(() => {
let initialPrices = {};
data.map(({ category, options }) => {
initialPrices = {
...initialPrices,
[category]: options[0].price,
};
});
setSelectedPrice(initialPrices);
}, []);
Upvotes: 1
Views: 1035
Reputation: 1724
From what I can see in your case, is that you want to populate initialPrices
, and after that to pass it setSelectedPrice
. The map
method is not a solution, for you in this case, because this method returns an array.
A safe bet in your case would a for in loop
, a forEach
, or a reduce
function.
const data = [
{
category: "ball",
options: [
{
price: "120.45"
}
]
},
{
category: "t-shirt",
options: [
{
price: "12.45"
}
]
}
];
The forEach example:
let initialPrices = {};
// category and options are destructured from the first parameter of the method
data.forEach(({ category, options}) => {
initialPrices[category] = options[0].price;
});
// in this process I'm using the Clojure concept to add dynamically the properties
setSelectedPrice(initialPrices);
The reduce example:
const initialPrices = Object.values(data).reduce((accumulatorObj, { category, options}) => {
accumulatorObj[category] = options[0].price
return accumulatorObj;
}, {});
setSelectedPrice(initialPrices);
Upvotes: 0
Reputation: 731
The map
function is intended to be used when you want to apply some function over every element of the calling array. I think here it's better to use a forEach
:
useEffect(() => {
let initialPrices = {};
data.forEach(({ category, options }) => {
initialPrices = {
...initialPrices,
[category]: options[0].price,
};
});
setSelectedPrice(initialPrices);
}, []);
Upvotes: 1
Reputation: 1018
The map
function must return a value. If you want to create a new object based on an array you should use the reduce
function instead.
const reducer = (accumulator, { category, options }) => (
{...accumulator, [category]:options[0].price}
)
const modifiedData = data.reduce(reducer)
More information https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Upvotes: 2
Reputation: 119
Your map
function should return something. Here it's not the case so the error happens. Maybe a reduce function will be more appropriate than map?
Upvotes: 1