E
E
embiid2020-07-17 12:20:45
React
embiid, 2020-07-17 12:20:45

How to initialize an empty array and pass it to props?

I am new to ReactJS. I'm building an application that takes JSON data from a file and stores it in the public folder.

class App extends React.Component {
  componentDidMount() {
    axios.get('http://localhost:3000/pizza.json').then(data => {
      store.dispatch(setPizza(data.Pizza))
    })
  }

  <Route path="/"     render    = { () => <Main items={ this.props.items }/>} exact></Route>


There is also routing, where on the main page I wanted to display the components. So I have an Item element:
function Item({ image, name, types, sizes, price }) {
  const availableTypes = ['0', '1'];
  const availableSizes = [26, 30, 40];

  const [activeType, setActiveType] = useState(types[0])
  const [activeSize, setActiveSize] = useState(sizes[0])

  const onSelectType = index => {
    setActiveType(index)
  }

  const onSelectSize = index => {
    setActiveSize(index)
  }

  return (
    <div className="item">
      <img src={ image } alt="pizza1" className="item-preview"/>
      <h3 className="item-name">{ name }</h3>
      <div className="item-dimantion">
        <ul className="list">
        {
          availableTypes.map((type, index) => (
          <li
            key={type}
            className={classNames({
              choice: true,
              active: activeType === index ? 'active' : '',
              disable: types.includes(index)
            })}
            onClick={() => onSelectType(index)}>
            { type }
          </li>
        ))}
        </ul>

        <ul className="list">
          {
            availableSizes.map((size, index) => (
              <li key={ size }
                  className={classNames({
                    choice: true,
                    active: activeSize === index ? 'active' : '',
                    disable: sizes.includes(index)
                  })}
                  onClick={() => onSelectSize(index)}>
                  { size } см.
              </li>
            ))
          }
        </ul>
      </div>

      <div className="more">
        <h4 className="price">от { price }</h4>
        <button className="add">Добавить</button>
      </div>
    </div>
  )
}


Then I call the Item component in Main
function Main({ items }) {
...
 <div className="main__content__items">
     {
        items.map(obj => {
           return (
              <Item key={obj}></Item>
           )
        })
      }
 </div>


And then it gives me an error: (TypeError: Cannot read property 'map' of undefined)

I decided, I then write items = [] in Main. I solved the problem, but when I check it, it displays false for me. How can I pass an array to a prop? console.log(Array.isArray(this.props.items))

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
TRNER, 2020-07-17
@embiid

componentDidMount is called after the component and all of its children are mounted (hence when we try to use props.items the json request hasn't even been sent yet).
We can assign an empty array for items in initialState to get rid of this error, or we can add an auxiliary state that would check if we have data loaded, and if so, display it.

P
Pavel Didenko, 2020-07-17
@Dasslier

Why can't you just call this request in componentDidMount on the Main page? What kind of perversion is it to call it in the App and pass it as a prop to the route?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question