0

I can't get this to work unfortunately and would very much appreciate some help :)

I get an array via POST request and want the elements of the array to be rendered in a list. I get the array, but it is not updating the useState as intended.

import React, { useEffect, useState } from "react";

const ShowFiles = () => {

    const [list, setList] = useState([])

    useEffect( () => {     
        fetch("https://--------------/getFiles", {
             headers: {
              'Content-Type': 'application/json'},
              method: 'POST',
              crossDomain:true,
        })
        .then( results => results.json())
        .then(data => {
            console.log(data)
            console.log("items:", data)
            setList(data)
            console.log("list:", list)
        })
       
    },[])

    return (

           
           <div>
            
           {list.map(({item}) => (
               <ul>{item}</ul>
           ))}
        </div>
    )
}

In the above example the list-variable stayed empty.

So I learned that useEffect needs a dependency variable, so I added "list" as such, which passed the array to the list-variable but it wouldn't stop making the POST request, so also not a solution.

Any idea in which direction I can get this to work?

Juno
  • 211
  • 5
  • 17
  • *"the list-variable stayed empty"* - What specific observation shows this? The line `console.log("list:", list)` is a mistake, but it won't prevent the component from working in general. Do you mean that the component itself never re-renders? And that `data` has been observed to indeed contain an array? Are there any errors in the browser's development console? – David Oct 07 '22 at 18:58
  • 1
    It's normal that you don't get the list data when you console log it in the useEffect because state updates are asynchronous but I don't see why the component itself wouldn't work please what does the console.log("items:" data) put in the console? – Lexus Oct 07 '22 at 18:59
  • you can check the putting the `log` outside the effect ... – KcH Oct 07 '22 at 19:03

2 Answers2

0

You cannot add list as a dependency in that particular useEffect because it will just create an endless loop by fetching and then refreshing the dom and the cycle continues.

You can resolve this by adding a new useEffect for list like so

useEffect(() => {
console.log(list);
}, [list])
otejiri
  • 1,017
  • 6
  • 20
0

You have passed {item} in place of item in .map function. It should be like this

<div>
            
           {list.map((item) => (
               <ul>{item}</ul>
           ))}
        </div>

Remove those extra curly {} braces

  • 1
    Unless the intent is to render a single property called `item` on each object in the array. We don't know, and the OP hasn't clarified anything. – David Oct 07 '22 at 19:10