A
A
Alexey Yakovlev2020-06-28 11:23:59
JavaScript
Alexey Yakovlev, 2020-06-28 11:23:59

Values ​​from json not found, how to fix?

I created a db.json file, started the server - json-server db.json
I get data using fetch:

import React from 'react';

import { Header, ToUsers, Activity } from './components';

function App() {
  const [activitys, setActivitys] = React.useState([]);

  React.useEffect(() => {
    fetch('http://localhost:3000/activitys')
      .then((data) => data.json())
      .then((json) => {
        setActivitys(json.activitys);
      });
  });

  return (
    <div className="app-wrapper">
      <Header items={['О комплексе', 'О компании', 'Новости', 'Медиа-банк', 'Контакты']} />
      <ToUsers />
      <Activity items={activitys} />
    </div>
  );
}

export default App;


In Activity I get data:
import React from 'react';

import '../styles/components/activity.sass';

import { ArrowBlackPng } from '../assets';
import { ActivityBlock } from '../components';

function Activity({ items }) {
  return (
    <div className="activity-wrapper">
      <div className="activity-wrapper__container">
        <div className="activity-wrapper__header">
          <div className="activity-wrapper-title">Текущие и будущие мероприятия</div>
          <a href="/more-activity" className="activity-wrapper-more">
            Все мероприятия
            <img src={ArrowBlackPng} alt="" />
          </a>
        </div>
        <div className="activity-wrapper__list-activitys">
            {items.map((obj) => (
                <ActivityBlock key={obj.id} {...obj} />
            ))}
        </div>
      </div>
    </div>
  );
}

export default Activity;


Error - TypeError: Cannot read property 'map' of undefined

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
profesor08, 2020-06-28
@aleshaykovlev

Use TypeScript and stuff like that will sort itself out. At the moment, anything can get into items, and the error will only come out at runtime.

T
twoone, 2020-06-28
@twoone

fetch, unlike react rendering, is an asynchronous operation, so by the time of the first render, items are undefined, and therefore the .map method also does not exist. The easiest way is to make items optional -
function Activity({ items = []}) {}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question