Masked Man
Masked Man

Reputation: 552

Axios doesn't GET data in React but it does in console

My JSON looks like this

{
    "towns" :[
        {
            "id" : 0,
            "location": "Japanifornia",
            "status" : 1
        },
        {
            "id" : 1,
            "location" : "Kohonohakatsuki",
            "status" : 2
        },
        {
            "id" : 2,
            "location" : "Taxis",
            "status" : 5
        }
        ]
}

The problem occured when I use axios in React. It should return the result like this.

[
    {
        "id": 0,
        "location": "Japanifornia",
        "status": 1
    },
    {
        "id": 1,
        "location": "Kohonohakatsuki",
        "status": 2
    },
    {
        "id": 2,
        "location": "Taxis",
        "status": 5
    }
]

The problem happened, I used axios in componentWillMount() in React to get request from localhost:7777/towns . But the request never been made, I checked the log from json-server and no request occured when I load or reload localhost:3000 which contains component that do GET request. I already check in other application ranging from Firefox to node console. All application return what it should beside React which return nothing

This is my componentWillMount

  componentWillMount() {
    axios.get('127.0.0.1:7777/towns')
    .then((res) => res.json())
    .then((result) => this.setState({data:result,isLoading: false}))
  }

Upvotes: 0

Views: 1611

Answers (2)

Masked Man
Masked Man

Reputation: 552

I found the solution finally!! It because of my stupid mistake.

I assumed the result is {[dataHere]} but it actually [] array.

The error occured because the result is JS array not Json array.

Upvotes: 1

davidyangsun
davidyangsun

Reputation: 69

documentation suggest to use Ajax call inside componentDidMount, inside componentWillMount u can initialize your data with an empy array. I think what you get from the call is an object with an attribute towns witch contains an array. To get the data try to set the state with result.towns. in componentDidMount do this.setState({ towns: result.towns}) and in componentWillMount do this.setState({ towns: []}). Add a console log in the render method and you should see the data.

Upvotes: 0

Related Questions