0

I'm trying to use axios.get() to fetch data from my database and I'm getting the response right, but when I try to assign the data into my state it doesn't seem to change the state.

import React, { Component, useState, useEffect } from 'react';
import TicketPanel from './TicketPanel';
import { Link } from 'react-router-dom';
import axios from 'axios';

export class Tickets extends Component {

    state = {
        tickets : []
    }

    componentDidMount() {
        axios.get('/issue-tracker/api/ticket/read.php').then(response => (
            this.setState({ tickets : response.data })
        )); 
    }   

I can't for the life of me figure out why it's not changing. The get() runs and the variable response.data I'm getting back looks like:

{
  "data": [
    {
      "id": "1",
      "title": "first issue",
      "description": "this is the first UI issue",
      "author": "rvagle",
      "status": "open",
      "category_id": "1",
      "category_name": "UI",
      "assigned_dev_id": null
    },
    {
      "id": "2",
      "title": "second issue",
      "description": "this is the first FE issue",
      "author": "rvagle",
      "status": "open",
      "category_id": "2",
      "category_name": "Front End",
      "assigned_dev_id": null
    },
    {
      "id": "3",
      "title": "3rd bug",
      "description": "this is the first BE issue",
      "author": "rvagle",
      "status": "open",
      "category_id": "3",
      "category_name": "Backend",
      "assigned_dev_id": null
    },
    {
      "id": "4",
      "title": "bug 4",
      "description": "this is the first config issue",
      "author": "rvagle",
      "status": "open",
      "category_id": "4",
      "category_name": "config",
      "assigned_dev_id": null
    }
  ]
}

Yet if I try to log state afterwards it remains the empty array.

Ricardo Gonzalez
  • 1,827
  • 1
  • 14
  • 25

1 Answers1

1

Yet if I try to log state afterwards it remains the empty array

setState is asynchronous.

You need to log it after the update is complete. The method takes a callback.

this.setState({ tickets : response.data }, () => console.log(this.state))
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335