JayDee
JayDee

Reputation: 102

How to save data from axios.get to hooks right away

How will I able to save in hooks that data from database. Since I need to display the data that I get to dropdown.

Here's my code

const [dataSystem, setdataSystem] = useState([])
const getAllSystems = async() => {
  ......
}

const getDependentSystems = async() => {
  const response = await axios.get('/API' + ID)
  console.log('LIST OF SYSTEM', response.data)
  setdataSystem(response.data)
}

Since upon setState, data is not yet saved to dataSystem I need to trigger getDeoendetSystems() twice to display the list on my dropdown.

Result of console.log

LIST OF SYSTEM [{...},{...}]
  0: {ID: 1, SYSTEMID: 12 ...},
  1: {ID: 2, SYSTEMID: 13 ...}

Thank you

Upvotes: 0

Views: 47

Answers (1)

Constantin Chirila
Constantin Chirila

Reputation: 2119

You need to load the data inside an useEffect like

function Component() {
    
  const [dataSystem, setdataSystem] = useState([])
  
  useEffect(() => {
  
   getDependentSystems()

  }, [])
  
  const getDependentSystems = async() => {
    const response = await axios.get('/API' + ID)
    console.log('LIST OF SYSTEM', response.data)
    setdataSystem(response.data)
  }
  
  
return ...
}

Basically you want to call the function in the useEffect so you only call it once; cause if you call it in the component context, everytime the state updates it will call the api again which will trigger an infinite loop.

Upvotes: 1

Related Questions