Reputation: 1539
I need to ask this question because tried to fix that issue couple of hours. Now I created a simple layout and this is has a sidebar. There is a navigation in this block. I'm trying to get list of coins and iterate them in to list element.
sidebar.jsx
export default {
Sidebar() {
return (
<div>
<h3>Coins</h3>
{
axios({
method: "GET",
url: "./ticker.json",
}).then(function (resp) {
let list = resp.data;
return Object.keys(list).map((key) => {
console.log(list[key].name);
return (<li key={key}>{list[key].name}</li>)
});
}).catch(function (errors) {
alert("Error thrown");
})
}
</div>
)
}
I imported that sidebar.jsx
in App.js
, you can see whole App.js
below
import Landing from './views/landing';
import Header from './components/header';
import Sidebar from './components/sidebar';
function App() {
return (
<div className="container-fluid">
{Header()}
<div className="row">
<div className="col-md-2">
{Sidebar.Sidebar()}
</div>
<div className="col-md-10">
{Landing(logo)}
</div>
</div>
</div>
);
}
export default App;
I'm getting below error. I can't understand how to fix it.
Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.
I know axios
return Promise
but I don't understand how to handle it.
If someone could help me, that I'll much appreciated.
Upvotes: 1
Views: 735
Reputation: 21297
Imperative code inside functional components must go inside useEffect
or similar custom hooks. You could store the response
in a state
variable. And render only when the data
get's resolved.
const App = () =>{
const [data, setData] = useState(null)
useEffect(() =>{
axios.get(url)
.then(res => setData(res.data))
},[])
return(
<div>
{
data && Object.keys(data).map((key) => {
console.log(list[key].name);
return (<li key={key}>{list[key].name}</li>)
})
}
</div>
)
}
Upvotes: 3