Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to rerender component, using useEffect and useState?

I’m trying to show a table in my react component, but i don’t know how to use useEffect and useState to render table in first render.

My component js:

import React, { useEffect, useState } from 'react'

const Projects = () => {
  const [tableData, setTableData] = React.useState()

  useEffect(() => {
    fetch('https://script.google.com/macros/s/AKfycbzuKuSOUfd9IOsQobix0PnIRv28IB3uTx5KdpVoVeNe04g7QzXQeeCEbsHBxE5CYdEV8A/exec') //получение информации из API гугла
        .then((response) => response.json()) //изменения формата в JSON
        .then((response) => {
          //запись значения JSON в переменную tableData
          setTableData(response['smr'])    
          console.log('Response in useEffect:')
          console.log(response['smr'])     // data is OK
          console.log('tableData in useEffect:')
          console.log(tableData)           // data is undefined
        }) 
  }, []);     

  return (
    <div>
    {/* {tableData.map(item => {
      <div key={item.is}>
        {item.adress}
      </div>
    })} */}
    </div>
  )
  
}

export default Projects

and i also use Routing in index.js:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
            <App />
        </PersistGate>
    </Provider>
);

>Solution :

Provided that your request completes sucesssfully, you can conditionally render the component like this"

 return (
    <div>
    {tableData && tableData.map(item => 
      (<div key={item.is}>
        {item.adress}
      </div>)
    )}
    </div>
  )

This way, the component only renders when tableData is not falsey (ie null or undefined).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading