skip to Main Content

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

2

Answers


  1. 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);
      }
    }
    
    Login or Signup to reply.
  2. 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>
          ))}
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search