Search code examples
reactjsgetaxioshttprequest

axios.get ERROR on using axios.create method by using baseUrl


I tried to create an application from an Random user API in react and I used axios library for HTTP Requests.I created a separate file for base API using axios.create and the file code goes as,

import axios from 'axios'

export default axios.create({
  baseURL: `http://jsonplaceholder.typicode.com`,
}); 

Then I used this in another file to make an GET request and store the data in state on componentdidMount so ill can access the data in UI.

import React from "react";
import API from "../api";
export default class PersonList extends React.Component {
  state = {
    persons: []
  };
  componentDidMount() {
    API
      .get('/').then((data) => {
      const persons = data.data;
      this.setState({ persons });
      console.log(this.state.persons);
    });
  }
  render() {
    const { persons } = this.state;
    console.log('Stato',persons)
    return (
      <ul>
        {persons.map((person) => (
          <li key={person.id}>{person.name}</li>
        ))}
      </ul>
    );
  }
}

But it doesn't work ,because the state is not filled up with Users data,so the .map() function is throwing an error.


Solution

  • You're encountering this error because of the URL you are using. In your example, you use https://jsonplaceholder.typicode.com as the endpoint in componentDidMount, but that isn't going to return any placeholder user data. I believe you meant to use https://jsonplaceholder.typicode.com/users instead.

    I have a working example here: https://codesandbox.io/s/axios-instance-ki9g6. Notice how I only had to change / in componentDidMount to /users.