Задать вопрос
@MarEeeeee

Как отрисовать данные которые приходят асинхроно?

Привет. Получаю данные из бд. Требуется отрисовать элементы как только они будут получены. Не понимаю как сделать это.
Мой компонент выглядит вот так
import React from 'react'
import  firebase from 'firebase';


class ListOfLecture extends React.Component{
    constructor(props) {
        super(props)
        this.state = {
            lectures:{},
            isLoading: false,
        }                    
      }



      async componentDidMount(){
        this.setState({
            lectures:(await firebase.database().ref('lectures/').once('value')).val(),
            isLoading: true
        }); 
    }


      render(){
          return(
              <div>
                  {
                     Object.keys(this.state.lectures).fill().map( (item,i)=>{
                         console.log(item, i)
                         return(<span key = {i}>{item}</span>)
                     })
                  
                  }
              </div>
          )
      }
}
export default ListOfLecture;

Значение внутри item undefined. я понимаю почему так происходит, но не понимаю как пофиксить
  • Вопрос задан
  • 122 просмотра
Подписаться 1 Простой 4 комментария
Помогут разобраться в теме Все курсы
  • Нетология
    Frontend-разработка на React
    10 недель
    Далее
  • ProductStar
    Разработка на React
    6 недель
    Далее
  • Яндекс Практикум
    React-разработчик
    3 месяца
    Далее
Решения вопроса 1
@tehfreak
Вот полная версия требуемого компонента с индикатором загрузки и обработкой ошибки:
class Lectures extends React.PureComponent {

    state = {
        lectures: null,
        lecturesError: null,
        lecturesPending: true,
    }

    async componentDidMount() {
        await this.fetchLectures()
    }

    async fetchLectures() {
        this.setState({ lectures:null, lecturesError:null, lecturesPending:true })
        try {
            const lectures = (await firebase.database().ref('lectures').once('value')).val()
            console.log(lectures)
            this.setState({ lectures, lecturesError:null, lecturesPending:false })
        } catch (lecturesError) {
            console.error(lecturesError)
            this.setState({ lectures:null, lecturesError, lecturesPending:false })
        }
    }

    render() {
        const { lectures, lecturesError, lecturesPending } = this.state
        return (
            <section>
                <h1>Лекции</h1>
                {lecturesPending && (
                    <div>Загружаются...</div>
                )}
                {lecturesError != null && (
                    <div>Не удалось загрузить: {lecturesError.message}</div>
                )}
                {lectures != null && (
                    <ul>
                        {lectures.map((lecture) => (
                            <li
                                key={lecture.id}
                            >
                                {lecture.name}
                            </li>
                        ))}
                    </ul>
                )}
            </section>
        )
    }
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы
от 250 000 до 300 000 ₽
ITK academy Нижний Новгород
от 50 000 до 90 000 ₽
ITK academy Екатеринбург
от 50 000 до 90 000 ₽