Home > Back-end >  fetch dosent bring any data
fetch dosent bring any data

Time:11-06

when i use fetch to bring the list of notes and consol.log it nothing shows up. The url is not wrong i have carefully checked it. Here is the code:

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

const NotesListPage = () => {

    let [notes, setNotes] = useState([])

    useEffect(() => {

    }, [])

    let getNotes = async () => {
        let response = await fetch('http://127.0.0.1:8000/api/notes/')
        let data = await response.json()
        console.log(data)
        setNotes(data)
    } 

    return (
        <div>
            
        </div>
    )
}

export default NotesListPage

here is the api part:

@api_view(['GET'])
def getNotes(request):
    notes = Note.objects.all()
    serializer = NoteSerializer(notes, many=True)
    return Response(serializer.data)

CodePudding user response:

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

const NotesListPage = () => {

    let [notes, setNotes] = useState([])

    useEffect(() => {
         getNotes();
    }, [])

    let getNotes = async () => {
        let response = await fetch('http://127.0.0.1:8000/api/notes/')
        let data = await response.json()
        console.log(data)
        setNotes(data)
    } 

    return (
        <div>
            
        </div>
    )
}

export default NotesListPage

CodePudding user response:

You are not calling your function 'getNotes'

The way I would do it, it to fetch your data in the Effect hook and set it in your state hook there.

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

const NotesListPage = () => {

    let [notes, setNotes] = useState([])

    useEffect( async () => {
        const response = await fetch('http://127.0.0.1:8000/api/notes/')
            .then(response => response.json())
            setNotes(response)
    }, [])

    console.log(notes)

    return (
        <div>
            
        </div>
    )
}

export default NotesListPage

*Edit

Cleaner would be to have the fetch in a seperate function doing the same thing and just calling that function in your effect hook (see other answer above*)

  • Related