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

useState set function doesn't work after fetch

import React, {useState, useEffect, useContext} from 'react'
import AuthContext from '../context/AuthContext'

const HomePage = () => {
  const [note,setNote] = useState([])
  let {authTokens} = useContext(AuthContext)
  useEffect(()=>{
    getNotes()
  },[])

  let getNotes = async () => {
    let response = await fetch("http://127.0.0.1:8000/api/notes",{
      method:"GET",
      headers:{
        "Content-type":"application/json",
        "Authorization":"Bearer "+String(authTokens.access)
      }
    })
      let data =await response.json();
      console.log("data i have been wait",data)
      
      console.log("Data in it",note)
  }

  return (
    <div>
        <p>You are logged in to home paage</p>
        {/* {notes.map(note =>{
          <li >{note.body}</li>
        })} */}
    </div>
  )
}

export default HomePage

I got my data from django backend and try to show in react using map but it doesnt map.
I can get the data but when I am trying to setNote(data) it doesn’t not work.
Sometimes it works but still cant map it. I cant refresh map func and put data on it

and I don’t get any error.[console.log like that][1]

      console.log("data i have been wait",data)
      
      setNote(data)
      console.log("Data in it",note)```


  [1]: https://i.stack.imgur.com/h17QF.png

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

>Solution :

In the case the setState works correctly but you can’t map the data, I suggest that the problem comes from the fact that you put brackets inside your map but no return.

Try this instead:

{notes.map(note =>
  {
    return(<li >{note.body}</li>);
  }
)}

or with arrow function:

{notes.map(note => <li>{note.body}</li>)}
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