Gazal Jain
Gazal Jain

Reputation: 49

Issue with incrementing index Counter inside useEffect Hook in ReactJS

In this part of code, I try to take a state variable 'lastIndex' and try to increment it using setlastIndex but the value of lastIndex doesn't increment and remains 0 . I am new to React Hooks, please help me. If such an exact query already been asked before in stack overflow then please send the link.

function App() {
  const [myAppointment, setmyAppointment] = useState([])
  **const [lastIndex, setlastIndex] = useState(0)** 
  const [orderBy, setorderBy] = useState('petName')
  const [orderDir, setorderDir] = useState('asc')
  const [queryText, setqueryText] = useState('')
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        **const apts=result.map(item=>{
          item.aptId = lastIndex
          setlastIndex(lastIndex => lastIndex+1)
          return item
        })**
        setmyAppointment(apts)
      })
  },[])

Upvotes: 0

Views: 758

Answers (1)

Dmitry Reutov
Dmitry Reutov

Reputation: 3032

You should understand that lastIndex doesnt increase each time you call setlastIndex function, so just declare it outside loop and increase each time assigning to aptId property. And after loop set state with the last value

then(result=>{
  let currentIndex = lastIndex
  result.forEach(item=>{
    item.aptId = ++currentIndex
  })
  setmyAppointment(result)
  setlastIndex(currentIndex)
})

map is not needed, you can use result to save it in setmyAppointments

Upvotes: 2

Related Questions