Cannot redeclare block-scoped variable 'response'

39 Views Asked by At

enter image description here

This a react app on sandbox, the button "load Data" was working, but when I refreshed sandbox, it gave me this error and the button is not fetching data now.

Also, I need to change the api link to this: https://reqres.in/api/users?page=1

but it gives error on this part : {users.map(({ id, login, avatar_url })

Kindly support.

import React, { useState } from "react";
import "./styles.css";

const App = () => {
  const [users, setUsers] = useState([]);
  const loadUsers = async () => {
    console.log("before");
    const response = await fetch("https://reqres.in/api/users?page=1");
    const jsonresponse = await response.json();
    setUsers(jsonresponse);
  };

  return (
    <div className="App">
      <h1>Hello All</h1>
      <button>Load Data</button>
      <h2>Users:</h2>
      <ul>
        {users.map(({ id, login, avatar_url }) => (
          <li key={id}>
            Name: {login} {avatar_url}
          </li>
        ))}
      </ul>
    </div>
  );
};
export default App;

I tried to change the variable name "response" but it didn't work.

Also, for uploading another api link, i tried to change users.map but it didn't work

1

There are 1 best solutions below

0
mssp On

I modified your code a bit and fixed the issue

The jsonresponse contains a json with data property which is an array of objects. You just have to set the array response to your state and it will render the necessary data. I also modified the users.map to include the avatar link and the first_name

Also you forgot to add an onClick on your Load Data button.


import React, { useState } from "react";
import "./styles.css";

const App = () => {
  const [users, setUsers] = useState([]);

  const loadUsers = async () => {
    const response = await fetch("https://reqres.in/api/users?page=1");
    const jsonresponse = await response.json();

    setUsers(jsonresponse?.data);
  };

  if (users?.length > 0) {
    return (
      <div className="App">
        <h1>Hello All</h1>
        <button onClick={loadUsers}>Load Data</button>
        <h2>Users:</h2>
        <ul>
          {users.map(({ id, first_name, avatar }) => (
            <li key={id}>
              Name: {first_name} {avatar}
            </li>
          ))}
        </ul>
      </div>
    );
  }
  return <></>;
};
export default App;