0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

As a follow up suggestion, using something like lodash or ramda can help clean up the errors thrown by map if the list you're trying to iterate over doesn't have the shape you expect. This doesn't fix your real issue, of course, but it can cut down on the type of errors that blow up in your face. I'll update my sandbox accordingly to show an example of this.
No problem. Glad I could help!

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.