Search code examples
javascriptreactjsamazon-dynamodbaws-appsyncaws-amplify

How to perform more than one query in reactjs and awsamplify


I'm tryig to querylist more than 1 Dynamo database in React.js. I have tried defining both components in different classes and importing them which didn't work then I tried defining both in thesame class which gives me the error

TypeError: this.state.patients2 is undefined

Here are my components

 state = { patients2: [] }


 async componentDidMount() {
    try {
      const apiData = await API.graphql(graphqlOperation(listPatients2))
      const patients2 = apiData.data.listPatients2.items
      this.setState({ patients2 })
    } catch (err) {
      console.log('qqqqqqqqqqqqqqqqqq ', err)
    } 
  } 

 state = { beraters: [] }
  async componentWillMount2() {
    try {
      const apiData = await API.graphql(graphqlOperation(listBeraters))
      const beraters = apiData.data.listBeraters.items
      this.setState({ beraters })
      console.log(beraters)
    } catch (err) {
      console.log('qqqqqqqqqqqqqqqqq ', err

)
    }
  } 

and here I map the results

<h1>Meine Daten</h1>


    {
          this.state.beraters.map((rest, i) => (
            <div style={styles.item}>
              <p style={styles.Vorname}>{rest.Vorname}</p>
              <p style={styles.Nachname}>{rest.Nachname}</p>
              <p style={styles.Strasse}>{rest.Strasse}</p>
              <p style={styles.Hausnr}>{rest.Hausnr}</p>
              <p style={styles.Ort}>{rest.Ort}</p>
              <p style={styles.Postleitzahl}>{rest.Postleitzahl}</p>
              <p style={styles.Telefonnummer}>{rest.Telefonnummer}</p>
            </div>
          ))
         }
      </div>

<div >
    {
          this.state.patients2.map((rest, i) => (
            <div style={styles.item}>
              <l style={styles.Vorname}>{rest.Vorname}</l>
              <l>  </l>
              <l style={styles.Nachname}>{rest.Nachname}</l>
            </div>
          ))


        }
      </div>

Any help is much appreciated. Thanks!


Solution

  • Your patients2 are undefined since you're overwriting state values. Just define your arrays in the state together as well as call your queries at the same time. Something like that:

    state = {
      beraters: [],
      patients2: []
    }
    async componentDidMount() {
        try {
          const apiDataPatients = await API.graphql(graphqlOperation(listPatients2))
          const apiDataBeraters = await API.graphql(graphqlOperation(listBeraters))
          const patients2 = apiDataPatients.data.listPatients2.items
          const beraters = apiDataBeraters.data.listBeraters.items
          this.setState({ beraters, patients2 })
        } catch (err) {
          console.log('Error:', err)
        } 
    }