skip to Main Content

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:

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

2

Answers


  1. 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).

    Login or Signup to reply.
  2. useState in react is a function that marks the value as dirty and so it triggers the rerender, only on the next rerender the actual value is updated. That means that if you print the value before the component is rerendered it will print the old value.

    You also want to initialize the state with an empty array otherwise it will error saying that map method doesn’t exists in an undefined object.

      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'])
              // tableData here has not yet changed the value so
              // it will print the initial value
            }) 
      }, []);     
    
      // if you want to print the values of tableData put a console log out of the useEffect
    
      return (
        <div>
         {tableData.map(item => 
          (<div key={item.is}>
            {item.adress}
          </div>)
        })
        </div>
      )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search