1

i want to get data (array) from /{url} and i tried this code

// Fetch the list on first mount
componentDidMount() {
this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {

fetch('/main')
.then(res => res.json())
.then(list => this.setState({ list }))
}

this is working fine but then i decided to switch to axios and tried literally same code

  // Fetch the list on first mount
componentDidMount() {
this.getList();
}

 // Retrieves the list of items from the Express app
 getList = () => {
 axios.get('/main')
.then(res=> res.json())
.then(list => this.setState({list}))

}

but it did not worked and gave me error in this line: .then(res=> res.json()) so i do not know what is problem if anyone knows the clue i will be glad if you tell me

3 Answers 3

3
// Fetch the list on first mount
componentDidMount() {
  this.getList();
}

// Retrieves the list of items from the Express app
getList = () => {
 axios.get('/main')
 .then(res=> res.data)
 .then(list => this.setState({list}))
 .catch(error => this.setState({error: error.message}))
}
Sign up to request clarification or add additional context in comments.

Comments

3

It is because axios has different response, instead of res.json() return data already like : return res.data or pass it to state directly something like

getList = () => {
 axios.get('/main')
   .then(res=> this.setState({list: res.data}))

4 Comments

it worked but can you tell my why? what type of response does axios have?
response from axios is data object (wrapper with lots of additional data) to access data served from express server you need to access data inside of taht object like response.data
and what type of instance is response from fetch?
here check axios docs github.com/axios/axios and this about fetch. scotch.io/tutorials/… ...
2

i would recommend some changes in your design, as im using axios successfully in many projects, its not a requirement but it helps and is working very reliable:

Create a service like api.js

import axios from 'axios';

export default axios.create({
  baseURL: `http://my.api.url/`
});

Then you can use it like this

import API from '../Services/api'; // this is your service you created before

LoadStats = async event => {
    try {
        var response = await API.get('api/targetroute');
        if (response.data != null) {
            this.setState({
                stats: {
                    mydata: response.data
                }
            });
            console.log('Receiving result: '+JSON.stringify(response.data));
        }
    } catch (error) {
        console.log('ERROR: '+error)
    }
}

9 Comments

thanks, as i noticed you modified code to async, but i thought axios was already async with Promise API
axios is always returning a promise so its always async the question here is how to handle the promise in your code. there are several ways to go, using subscriptions or handling promises with then /catch or using async decorator are all handling promises with a different software design. i usually prefer using the async decorator as im coming from c# and i like the programming flow it allows.. of course sometimes its better to just subscribe to the event i personally think promise chaining then / catch is a nogo as its an absolute mess, but this is my personal opinion
if you ask me there is no need for baseUrl, (at least in my case) because i am not using it and it still not blocking Cross Origin Request
i like it clear and beauty so by consuming several api's / routes / services i only have to change the base url servers change etc.. usually you have several routes per api to consume so overall all routes have a base url of course this is a personal design thing, do it how you like :) what do you mean by ...still not blocking CORS ?
i upvoted you and your comment too, maybe there is problem in Stackoverflow
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.