Search code examples
django-rest-frameworkhookuse-state

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.sstatic.net/h17QF.png

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>)}