V
V
vertically-challenged2022-03-31 23:48:54
React
vertically-challenged, 2022-03-31 23:48:54

State is updated but no rendering happens, how to fix it?

In the addRecord function, I change the data on the server and I immediately need to get and display this new data, but the data is drawn only after the second call to this function, how can I fix this? Why is this happening?

import React, { useState, useEffect} from 'react'
import './App.scss'
import API from './API/api'
import Table from './modules/Table/Table'
import Button from './modules/common/Button/Button'
import mainConfig from './mainConfig'


const addRecord = (setRecords) => {
  const newRecord = {data:{}}
  for (let field of mainConfig.fields) {
    newRecord.data[field] = ''
  }
  API.addRecord(newRecord).then(() => {
    API.getData().then(records => {
      setRecords(records)
    })
  })
}

function App() {
  const [records, setRecords] = useState({})
  const [modifiedFields, setModifiedFields] = useState([])

  useEffect(() => {
    API.getData().then(records => {
      setRecords(records)
    })
  }, [])


  return (
    <div>
      {records !== undefined && <Table records={records} setRecords={setRecords} modifiedFields={modifiedFields} setModifiedFields={setModifiedFields}/>}
      <Button name={'Add record'} onClick={() => addRecord(setRecords)}/>
    </div>
  )
}

export default App

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
deantek, 2022-04-01
@vertically-challenged

you're calling the hook outside of the App component, of course it won't update, hooks can't be used like that

A
Alexandroppolus, 2022-04-01
@Alexandroppolus

API.addRecord(newRecord) works asynchronously. We must wait for it to complete, and only then make an API.getData () request

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question