Home > Mobile >  getting undefined value of imported function in react
getting undefined value of imported function in react

Time:12-11

I am filtering data based on texts typed in the searchbox. I am first filtering the data and then mapping it. My code is working is as expected but there is the repetition of a function so I put it into the util folder and then use it in the file. But the problem is that the value I am getting is undefined from that util function.

Previous code of Members.js:

import React from 'react'
import members from '../members.json'

function Member({searchTerm}) {
  return (
    <div>
      {
        members.filter((ele) =>
                ele.first_name
                  .toLowerCase()
                  .includes(searchTerm.toLocaleLowerCase()) ||
                ele.last_name
                  .toLowerCase()
                  .includes(searchTerm.toLocaleLowerCase()))
        .map(ele => {
          return (
            <div key={ele.id}>
              <h1>Name: {ele.first_name} {ele.last_name}</h1>
            </div>
          )
        })
      }
    </div>
  )
}

export default Member

My new approach with Utils

utils/helper.js:

const searchMembers = (membersArr, searchTerm) => {
  return membersArr.filter(
    (ele) =>
      ele.first_name
        .toLowerCase()
        .includes(searchTerm.toLocaleLowerCase()) ||
      ele.last_name.toLowerCase().includes(searchTerm.toLocaleLowerCase())
  );
}

export { searchMembers }

Members.js

import React from 'react'
import members from '../members.json'
import {searchMembers} from '../utils/helper'

function Member({searchTerm}) {
  const {searchMember} = searchMembers(members, searchTerm)
  console.log('searchMember:', searchMember)      //undefined
  return (
    <div>
      {
        searchMember.map(ele => {
          return (
            <div key={ele.id}>
              <h1>Name: {ele.first_name} {ele.last_name}</h1>
            </div>
          )
        })
      }
    </div>
  )
}

export default Member

For above approach I am getting error searchMember.filter is not a function.

Can you guys please help me?

Thank you

CodePudding user response:

Your searchMembers method returns the filtered results directly. While your code

const {searchMember} = searchMembers(members, searchTerm)

tries to extract a searchMember from the returned data (through destructuring).

use

const searchMember = searchMembers(members, searchTerm)
  • Related