Home > Net >  Undefined when selecting div with information
Undefined when selecting div with information

Time:04-01

Having an issue with a piece of my code. I fetch from flask server, and display with div in React. I want to select the div and have that information pass to a new object array to return back to flask, but I keep getting undefined.

Code snippet:

function PLCPage() {
  const [myjunk, setMyjunk] =  useState([]);
  const [devList, setDevList] = useState ([]);

  const Scan = () => {
    fetch('/api/home').then(response => {
      if(response.status === 200){
        return response.json()
      }
    })
    .then(data => setMyjunk(data))
    .then(error => console.log(error))
  }

  const Clear = () => {
    setMyjunk({})
  }

Creating the divs:

{Object.keys(myjunk).map((key) =>{
  return ( 
    <div className='plc-container' key={key} onClick={ReadStuff}>
      <h1>ID:{myjunk[key]['name']}</h1> 
      <h1>IP:{myjunk[key]['IP']}</h1>                      
    </div>
  )

Clicking on the div, just to return a console log returns undefined.

const ReadStuff = () => {
  console.log(this.IP)
}

I eventually want to return the data I have in the 2 h1 tags to a new object (devList) but I can't even get it to console log. Sorry if this is basic but I've been stumped at this for a week. Thanks

I've tried this.IP, myjunk.IP, this,myjunk.IP. myjunk['IP']. Nothing returns. And when I do myjunk.IP I get "cant read from undefined"

CodePudding user response:

One way to do this is to create a separate component:

const JunkButton = ({junk}) => (
    <div className='plc-container' key={key} onClick={() => ReadStuff(junk)}>
        <h1>ID:{junk['name']}</h1> 
        <h1>IP:{junk['IP']}</h1>
    </div>
)

Now your map() looks like:

{Object.keys(myjunk).map((key) =>{ <JunkButton junk={ myjunk[key] }/> }

And ReadStuff becomes:

const ReadStuff = (junk) => { console.log(junk) }

Notice how in React we explicitly pass things around as props or function parameters.

CodePudding user response:

first you need to pass myjuck to function and then console it like this:

{Object.keys(myjunk).map((key) =>{
          return (
    // sending myjuck to function whatever that is
            <div className='plc-container' key={key} onClick={() => ReadStuff(myjunk)}>
              <h1>ID:{myjunk[key]['name']}</h1> 
              <h1>IP:{myjunk[key]['IP']}</h1>                      
            </div>
          )

ReadStuff function

   const ReadStuff = (myjunk) => { console.log(tmyjunk) }
  • Related