Reputation: 174
I'm trying to render an object with an array into an array (a JSON), that I receive from an API. I've tried a lot but I don't get with the solution.
This is the object format I receive:
{
"catalogue": [
[
"shoes.txt",
"trousers.txt",
"tshirts.txt"
]
]
}
This is the code I'm using to call the API and render the object:
import React, { Component } from "react";
import axios from "axios";
class Result extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
componentDidMount() {
const URL = "http://localhost/catalogue";
fetch(URL)
.then((response) => response.json())
.then((data) => this.setState({ items: data }));
}
render() {
const catalogue = this.state.items.catalogue;
return <div>{catalogue}</div>;
}
}
export default Result;
The only I could show in the web is this:
shoes.txttrousers.txttshirts.txt
The view I can get is something like this:
shoes.txt
trousers.txt
tshirts.txt
Would somebody help me please? Thanks in advance.
Upvotes: 0
Views: 1972
Reputation: 3285
Try this:
import React, { Component } from "react";
class Result extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
componentDidMount() {
const URL = "http://localhost/catalogue";
fetch(URL)
.then((response) => response.json())
.then((data) => this.setState({ items: data.catalogue[0] }));
}
render() {
let catalogue = this.state.items.map((item, key) => (
<li key={key}>{item}</li>
));
return <ul>{catalogue}</ul>;
}
}
export default Result;
Pay attention to the "[0]" in this line:
.then((data) => this.setState({ items: data.catalogue[0] }));
Upvotes: 1
Reputation: 1488
Just change the render method to
class Result extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
};
}
componentDidMount() {
const URL = "http://localhost/catalogue";
fetch(URL)
.then((response) => response.json())
.then((data) => this.setState({ items: data.catalogue }));
}
render() {
return(
<div>
{this.state.items.catalogue.map((item, index) => (
<span key={index}>{item}</span>
))}
</div>
)}
Upvotes: 0
Reputation: 426
I'm not 100% sure this is what you're looking for, but this should set you on the right track to achieving what you want eventually
Change
return <div>{catalogue}</div>;
to
return (
<div>
{catalogue.map(item => (
<div key={item}>{item}</div>
)}
</div>
);
This will render your each entry in your array as a separate
Upvotes: 0