nastidev
nastidev

Reputation: 25

React Cannot read property 'then' of undefined in componentDidMount

I'm fetching using two APIs in componentDidMount. The second fetch needs ID from the first fetch to get fetched.

The first fetch works well, but when I want to map through it for the second fetch, I get an error : Cannot read property 'then' of undefined

A portion of Orders json is below:

{
    "orders": [
        {
            "deadline": 1563046159,
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            "id": "83f007d6",
            "name": "Work order 83f007d6",
            "workerId": 1
        },
        {
            "deadline": 1562752687,
            "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
            "id": "cb23c526",
            "name": "Work order cb23c526",
            "workerId": 1
        },
]
}

And worker json is below:

{
    "worker": {
        "companyName": "Topiczoom",
        "email": "[email protected]",
        "id": 0,
        "image": "http://dummyimage.com/250x250.jpg/ccccff/000000",
        "name": "Frans Storie"
    }
}

class App extends Component {

constructor(props) {
  super(props);
  this.state={
    ordersData: [],
    workersData:[]
  }
} 


  componentDidMount() {

    fetch("https://www.hatchways.io/api/assessment/work_orders")
      .then(response => response.json())
      .then(data => {
        this.setState({
          ordersData: data.orders
          });
          console.log(this.state.ordersData)
          .then(this.state.ordersData.map(order =>{
            console.log(this.state.ordersData)
           fetch(`https://www.hatchways.io/api/assessment/workers/${order.workerId}`)
            .then(result => result.json())
            .then( data2 =>{
              this.setState ({
                workersData : data2.worker
              })
            })
          }))
          console.log(this.state)
        })
      .catch(err => {
        console.log(err)
      }); 
  }

Cannot read property 'then' of undefined

Upvotes: 0

Views: 193

Answers (1)

ravibagul91
ravibagul91

Reputation: 20765

You cannot use .then directly without fetch inside of fetch as you did.

You need a callback in setState to call another API based on state set from first API response,

fetch("https://www.hatchways.io/api/assessment/work_orders")
    .then(response => response.json())
    .then(data => {
        this.setState({
            ordersData: data.orders
        }, () => { //callback of setState, now here you can access state
            console.log(this.state.ordersData)
            this.state.ordersData.map(order => {
                console.log(this.state.ordersData)
                fetch(`https://www.hatchways.io/api/assessment/workers/${order.workerId}`)
                    .then(result => result.json())
                    .then(data2 => {
                        this.setState({
                            workersData: data2.worker
                        }, () => console.log(this.state))
                    })
            })
        });
    })
    .catch(err => {
        console.log(err)
    });

Update

To store all the records,

 () => { //callback of setState, now here you can access state
            console.log(this.state.ordersData)
            let workersData = [];
            this.state.ordersData.map(order => {
                console.log(this.state.ordersData)
                fetch(`https://www.hatchways.io/api/assessment/workers/${order.workerId}`)
                    .then(result => result.json())
                    .then(data2 => {
                        workersData.push(data2.worker)
                    })
            })
            this.setState({
                   workersData
            }, () => console.log(this.state))
        });

Upvotes: 1

Related Questions