N
N
Nikita Shchypylov2017-12-11 11:13:04
React
Nikita Shchypylov, 2017-12-11 11:13:04

Why does nothing come out when trying to display items from Firebase?

Hello everyone
I can not display items from the firebase. In AC - outputs, in reducer - outputs, but not in the component.
The code :

componentDidMount() {
    const ideas = firebase.database().ref("items");
    let arr = [];
    ideas.on("value", snapshot => {
      let items = snapshot.val();
      for (let item in items) {
        arr.push({
          id: item,
          text: items[item].text
        });
      }
    });
    this.props.renderIdeas(arr);
  }

AC :
export function renderIdeas(ideas) {
  return {
    type: RENDER_IDEAS,
    payload: ideas
  };
}

Reducer :
export default function(state = [], action) {
  switch (action.type) {
    case RENDER_IDEAS:
      return action.payload;
    default:
      return state;
  }
}

UPD:
It turns out that everything is in order, but I can't even output the data with console.log.
Here is my code:
render() {
    var Items = this.props.ideas;
    console.log(Items); //это выводит в порядке
    for (var key in Items) {
      console.log(key); //это уже не работает
    }
}

The output looks like this:5a2e42d63d792569224622.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2017-12-11
@Nikulio

The code in componentDidUpdate is not correct, you can fix it like this:

componentDidMount() {
    const ideas = firebase.database().ref("items");
    let arr = [];
    ideas.on("value", snapshot => {
      let items = snapshot.val();
      for (let item in items) {
        arr.push({
          id: item,
          text: items[item].text
        });
      }
      this.props.renderIdeas(arr);
    });
  
  }

The reason is asynchrony . He rendered your component before the completion of the on value callback . Since you passed a link to the array, it was displayed and updated in the console, but the render passed with an empty one.
Iterating arrays for in is not recommended, the order of elements may be violated. For objects it is also better to use Object.keys(obj).map
reducer for render should not be used.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question