-1

I'm using Fetch to get data from a json server and save it in the connection constant. After getting the data, I use connection.json() to transform the json into a javascript object. But I can't map this object, because it is an Object with an array inside. I would like to turn it into an array of objects. How should I proceed?

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

  async function list(){
    try{
      const connection = await fetch("https://my-json-server.typicode.com/priscilasilvaalves/priscilasilvaalves.github.io/db");
      const list = await connection.json();
      setItems(list);
      console.log(items); // Returns an Object with an array inside
    }catch(error){
      console.log(error);
    }
  }
Priscila
  • 45
  • 1
  • 7
  • Firstly where you `console.log(items)` that **will not** be the value you just passed to`setItems` (https://stackoverflow.com/q/38558200/3001761). But secondly if you want to access the property of an object you do it the same way here as anywhere else - use dot `foo.bar` or bracket `foo["bar"]` notation. – jonrsharpe Jul 23 '23 at 16:15
  • Whats the model you are getting the connection? – Selaka Nanayakkara Jul 23 '23 at 16:16

2 Answers2

0

the response contains the node lista. If you access it directly, you will get the desired result.

async function list(){
  try{
    const connection = await fetch("https://my-json-server.typicode.com/priscilasilvaalves/priscilasilvaalves.github.io/db");
    const list = await connection.json();
    setItems(list.lista); // Access the 'lista' property directly
    console.log(items);
  }catch(error){
    console.log(error);
  }
}
Maik Thiele
  • 505
  • 2
  • 10
-1

if you want to render the array of objects, you can use something like this,

  const [items, setItems] = useState([]);
  async function list() {
    try {
      const connection = await fetch(
        'https://my-json-server.typicode.com/priscilasilvaalves/priscilasilvaalves.github.io/db'
      );
      const list = await connection.json();
      setItems(list.lista);
      console.log(list.lista); // used this to get access of the array
    } catch (error) {
      console.log(error);
    }
  }

return (
      {item.map((i) => (
        <span>
          <div>{i.id}</div>
          <div>{i.nome}</div>
        </span>
      ))}
)
Sanu Kumar
  • 86
  • 7