Search code examples
reactjsreact-hooksfrontendfetch

how to use react fetch() with useEffect hook and map the fetched data


Trying to fetch api data on frontend using useEffect hook,

i am able console log the data but unable to map it somehow

new to react

console output

function SlugBook() {
    // let {slug} = useParams(),
    const [state, setState] = useState([])
    
    useEffect(() => {
        fetch("http://127.0.0.1:8000/app/reviews/",{CSRF_TOKEN....}
            )
            .then(response => response.json()) 
            .then(data => console.log(data)) -->works fine
            .then(data => setState(data)); --> not sure
        
           })

         return (
               <p>
            {state.map( d => (<li>{d}</li>))} ---> error code ()
               </p>
            )
            }
 export default SlugBook

Solution

  • Two problems:

    1. You need to set your state inside the second then like so:
        useEffect(() => {
            fetch("http://127.0.0.1:8000/app/reviews/",{
                credentials: 'include',
                method: 'GET',
                mode: 'same-origin',
                headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
                  'X-CSRFToken': CSRF_TOKEN
                }})
                .then(response => response.json()) 
                .then(data => setState(data))
        })
    
    1. You need to use a dependency array in your useRef or else you will get infinite re-renders. So change it to:
        useEffect(() => {
            fetch("http://127.0.0.1:8000/app/reviews/",{
                credentials: 'include',
                method: 'GET',
                mode: 'same-origin',
                headers: {
                  'Accept': 'application/json',
                  'Content-Type': 'application/json',
                  'X-CSRFToken': CSRF_TOKEN
                }})
                .then(response => response.json()) 
                .then(data => console.log(data)) -->works fine
                .then(data => setState(data)); --> not sure
    
            
        }, [])
    

    Setting the dependancy array to an empty array [] will ensure that your useEffect only runs your fetch once on first render.