Reputation: 11
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!
Upvotes: 1
Views: 4853
Reputation: 2783
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>
);
}
Upvotes: 1
Reputation: 924
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>
Upvotes: 0