Empty object response on fetching data from a local JSON server in React.

huangapple go评论63阅读模式
英文:

Empty object response on fetching data from a local JSON server in React

问题

我试图显示来自本地JSON服务器的数据,但遇到了错误。

我知道fetch返回一个异步的promise,并且需要几毫秒才能成功获取数据,但我的问题是,我如何避免或忽略第一个空对象响应,只在数据成功获取后执行map,因为我得到了“Cannot read properties of undefined (reading 'map')”错误。
英文:

I`m trying to display the data from a local JSON server but I get into errors.

I know that fetch returns a promise which is asynchronous and it takes couple of milliseconds to succesfully fetch the data but my question is, how can I avoid or ignore the first empty object response and only execute the map on the data when it`s fetched because I get "Cannot read properties of undefined (reading "map)"

function App() {
  const [data, setData] = useState({});
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    fetch("http://localhost:8000/data")
      .then((response) => {
        if (!response.ok) {
          throw new Error("Data failed to fetch");
        }
        return response.json();
      })
      .then((data) => {
        setData(data);
        setLoaded(true);
      });
  }, []);

  return (
    <div className="App">
      <Card data={data} loaded={loaded} />
    </div>
  );
}

const Card = ({ data, loaded }) => {
  return (
    <div>
      {data.activeUsers.user432.map((user) => (
        <h1 key={user.id}>{user.id}</h1>
      ))}
    </div>
  );
};

答案1

得分: 0

尝试这个 -

{ data.activeUsers?.user432.map((user) => (
        <h1 key={user.id}>{user.id}</h1>
      ))}
英文:

try this -

{ data.activeUsers?.user432.map((user) =&gt; (
        &lt;h1 key={user.id}&gt;{user.id}&lt;/h1&gt;
      ))}

huangapple
  • 本文由 发表于 2023年5月24日 22:07:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76324446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定