Home > Blockchain >  Array.some is not working inside my React component, but Array.map is
Array.some is not working inside my React component, but Array.map is

Time:08-04

I'm trying to use Array.prototype.some() inside my React component to determine if my array of objects has a certain value, but I'm getting the error data.some(...) is not a function. Array.prototype.map() is working fine.

My data is an array of objects from MongoDB.

data = [
 {_id: 'foobar', category: 'sleep'}, {}, ...
]

Here's the component with the props being passed down:

<Component
  data={data}
  category='sleep'
/>

The component:

import ChildComponent from "../components/ChildComponent";

const Component = ({ data, category }) => {
  return ( 
    <>
      {data && data.some(e => e.category === category) (
        <h3>{category}</h3>
      )}

      {data && data.map(e => {
        return gear.category === category &&
          <ChildComponent 
            key={e._id} 
            e={e}
          />
      })}
    </> 
   );
}
 
export default Component;

Why would .map work but not .some?

CodePudding user response:

Array.map(...) returns an array. Array.some(...) returns a boolean.

CodePudding user response:

Made a mistake with the logic, should be:

{data && data.some(e => e.category === category) && <h3>{category}</h3>}
  • Related