Home > Enterprise >  Data undefined after refresh
Data undefined after refresh

Time:04-30

I have an issue with my react and express/mongodb app where the first load miscData is not defined (which is the name of my collection in my mongodb database), but when I comment out all the paragraph tags and only console.log(getBasic) I am able to log it (when before I was unable to log it due to it being undefined) and then when I uncomment the paragraph tags I am able to see them now, that is until I refresh which resets this.

I have a console.log statement and then 3 html paragraphs that display the blogTitles. When I first boot it doesn't work until I do the comment save, uncomment save, refresh method mentioned above.

Here is a 1 minute video that shows what I am talking about if that didn't make much sense.

App.js:

function App() {

  const [getBasic, setGetBasic] = useState()

  async function fetchData() {
    await axios.get('http://localhost:3001/api')
    .then(result => setGetBasic(result.data))

    
  }



  useEffect(() => {
    fetchData()
  }, [])

  

  return (
    <div className="App">

      <p>{JSON.stringify(getBasic.miscData[1].blogTitle)}</p>
      <p>{JSON.stringify(getBasic.miscData[2].blogTitle)}</p>
      <p>{JSON.stringify(getBasic.miscData[3].blogTitle)}</p>
      {console.log(`getBasic ${JSON.stringify(getBasic)}`)}

    </div>
  );
}

export default App;

server.js:

app.get('/api', (req, res) => {
  res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  db.collection('miscData').find().toArray((err, result) => {
      if (err) return console.log(err)
      res.send({ miscData: result })
  })
})

This is what miscData looks like:

getBasic {"miscData":[{"_id":"62604421b57b621bda4171c7","blogTitle":"Different title","blogBody":"lorem ipsum etc etc etc"},{"_id":"626058bb61967575695bdade","blogTitle":"Com squadron","blogBody":"asidjaoisdoasodjiaosjdoia"},{"_id":"626059f961967575695bdadf","blogTitle":"test","blogBody":"test"},{"_id":"62605a3d36e02b8581f56154","blogTitle":"asdasda","blogBody":"adadada"},{"_id":"62608bc60bd6de526fd1b0bc","blogTitle":"new title","blogBody":"new body"}]}

My React is port 3000, and server is 3001

CodePudding user response:

Actually the method fetchData() is an asynchronous call, i.e., the term asynchronous refers to two or more objects or events not existing or happening at the same time (or multiple related things happening without waiting for the previous one to complete) link.

Whereas the <p> tags are synchronous code, they render even before your data is fetched from the backend. Hence you receive undefined for a while and as soon as it is fetched, the <p> tags get populated and you can see them. This also explains why it resets when you refresh it.

  • Related