1

I have been trying to make an api call and receive the data back as an array to iterate over the array and populate react components. The problem is I am only receiving promises back, and therefore react will not let me use the map function. I am newer to react and am having trouble understanding the problem.

I am making the axios call as below:

const makeRequest = async (url) => {
  return await axios.get(url).then(response => response.data);
}

And then attempting to save the array response inside a variable to be iterated over.

let data = makeRequest("someUrl");

If I have a console.log() call inside the request, I can get the array, but as soon as I try to save it to the variable I am only getting the promise. Any help would be great thank you!

0

2 Answers 2

1

You need to use a state variable in order to handle async data.

In your component you can iterate over the array from the state variable and so once your data is ready you can update the state variable and your component will automatically re-render.

import React, { useEffect, useState } from "react";
import axios from "axios";

function DisplayData() {
  // initialize data state variable as an empty array
  const [data, setData] = useState([]);

  // make the fetch the first time your component mounts
  useEffect(() => {
    axios.get(url).then(response => setData(response.data));
  }, []);

  return (
    <div>
      {data.map((row) => (
        <p key={row.id}>{row.content}</p>
      ))}
    </div>
  );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks a bunch! This solved my problem without the constant re-renders, really appreciate it
@BrandonGullion In the latest version of react, returning a promise from useEffect will throw an error and I've updated my answer to reflect that
@BrandonGullion if this solved your problem, then accept this answer as correct.
0

Please take reference from below example, this might be usefull:

// api.js
import axios from 'axios';

export default axios.create({
  baseURL: `xyz`
});

// PersonList
import React from 'react';
import axios from 'axios';

export default class PersonList extends React.Component {
  state = {
    id: '',
  }

  handleChange = event => {
    this.setState({ id: event.target.value });
  }

  handleSubmit = async event => {
    event.preventDefault();

    const response = await API.get(`xyz`);
    console.log(response);
    console.log(response.data);
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <label>
            Person ID:
            <input type="text" name="id" onChange={this.handleChange} />
          </label>
          <button type="submit">Delete</button>
        </form>
      </div>
    )
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.2.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.2.0/react-dom.min.js"></script>
<div>

Comments

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.