0

I am trying to make a really simple api call without any logic at all.Althoough I get an illegible object in the consoel called 'proxy' at leaset (not expected either) I cant return anything in the render() method and it throws a typeError. my code:

Store:

import {observable, configure, action,flow, computed, decorate, set, runInAction} from 'mobx';
import {observer, inject} from 'mobx-react'
configure({enforceActions:'observed'})

class GenStore {
  verseData = []
  state = "pending"

  getVerseData = flow(function*() {
      this.verseData = []
      this.state = "pending"
      try {
          const response = yield fetch('https://api.quranwbw.com/2/10') 
          const data = response.json()
          this.state = "done"
          this.verseData = data 
      } catch (error) {
          this.state = "error"
      }
  })
}

decorate(GenStore, {state:observable, verseData: observable, getVerseData:action})

  export default new GenStore()

Retrieval:

import {observable, configure, action,flow, computed, decorate, set, runInAction} from 'mobx';
  import { computedFn } from "mobx-utils"
  import {observer, inject} from 'mobx-react'
  import React from 'react'
  import GenStore from './GenStore'

class Show extends React.Component{
    componentDidMount(){
      this.props.GenStore.getVerseData()
    }
    render(){
      console.log(this.props.GenStore.verseData)
    return <h1>{this.props.GenStore.verseData.words[0].word_arabic}</h1>
    }
  }
  export default inject('GenStore')(observer(Show))

error returned when i try to render: TypeError: Cannot read property '0' of undefined

Any help would be appreciated. Thanx in advance. Oh, and if you have any suggestion as to how to implement this call if you think flow isnt the choice method, please advise me and tell me how i can do it best

General Grievance
  • 4,555
  • 31
  • 31
  • 45

1 Answers1

0

Because getVerseData is async function and when component renders for the first time verseData is an empty array (why it is empty array though? It should be empty object) and respectively verseData.words is undefined.

You can do several things to deal with it, for example, check if verseData.words exists and if not show some loader component instead.

Danila
  • 15,606
  • 2
  • 35
  • 67