How can I use useEffect correctly in a function?

Viewed 65

I don't think I am using useEffect correctly in the function I have written. If I do the same with classes there is no problem and I am able to do ComponentDidMount(). But I don't know Hooks very well. So I think I am going wrong somewhere.

//import { onValue } from 'firebase/database';
import React, { useEffect } from "react";
import {db} from '../../firebase';
import {ref,onValue} from 'firebase/database'
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';

export default function NiftyChart() {
 React.useEffect(()=>{
    const dbRef=ref(db,"1rh1Ta-8dqZKmh1xy5ans2lOqReoiVAT81WyDKqRaxl0/Nifty");
    onValue(dbRef,(snapshot)=>{
      let records=[];
      snapshot.forEach(childSnapshot=>{
        let keyName=childSnapshot.key;
        let data=childSnapshot.val();
       console.log(snapshot.val());

        records.push({"key":keyName,"data":data})
        console.log(records[records.length-1])
      });
      this.setState();
 })
},[]); 
  
  
    return(
        
      <div>
{this.state.map((row, index)=>{
return(
<Box component="span" sx={{}}>
<Grid > {row.Close}</Grid>


</Box>
)
})}
</div>
    )
  }

Also, no value is printed for row.Close. In the console I seem to be getting Cannot read properties of undefined (reading 'state') this error. Any help is appreciated.

1 Answers

You need to use useState:

const [records, setRecords] = useState([]);

useEffect(() => ..get records and set to state, []);

So code would look like this:

export default function MyComponent() {
  const [records, setRecords] = useState([]);
  

  useEffect(() => {
    // ... other code is omitted for the brevity
    setRecords(records)
  }, [])


  return(            
      <div>
          {records && 
              records.map((row, index)=>{ //...other code is omitted 
              // for the brevity }
      </div>
  )
}

What's hook? The hook is:

A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components

[] in useEffect means:

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

Read more about API call in this great article

Related