1
Hello, I’m studying React JS trying to make an application with the API of the CEP. However, I saw that the JSON of it is an object and does not have an array, therefore, I am not able to perform the map (is giving "...map is not a Function") to print the information in the browser.
{
"cep": "20260-080",
"logradouro": "Rua Joaquim Palhares",
"complemento": "até 392/393",
"bairro": "Estácio",
"localidade": "Rio de Janeiro",
"uf": "RJ",
"unidade": "",
"ibge": "3304557",
"gia": ""
}
I tried to settle with a Array.() before the map and a JSON.parse() in the fetch, but without success.
class App extends Component {
constructor(props) {
super(props)
this.state = {
result: null,
searchTerm: '',
}
this.onSearchChange = this.onSearchChange.bind(this)
this.onSearchSubmit = this.onSearchSubmit.bind(this)
}
fetchSearchTopStories(searchTerm) {
fetch(`https://viacep.com.br/ws/${searchTerm}/json/`)
.then(res => res.json())
.then(result => this.setState({result}))
.catch(err => err);
}
onSearchChange(e) {
this.setState({ searchTerm: e.target.value });
}
onSearchSubmit(e) {
const { searchTerm } = this.state;
this.fetchSearchTopStories(searchTerm)
e.preventDefault()
}
componentDidMount(){
const { searchTerm } = this.state;
this.fetchSearchTopStories(searchTerm)
}
render(){
const {result, searchTerm} = this.state
return (
<>
<form onSubmit={this.onSearchSubmit}>
<input type='text' value={searchTerm} onChange={this.onSearchChange}/>
<button type='submit'>Clique</button>
</form>
{result?
<div>
{result.map((item, index) =>
<span key={index}>
<p>{item.logradouro}</p>
<p>{item.bairro}</p>
<p>{item.localidade}</p>
</span>
)}
</div>
:null}
</>
);
}
}
I would be very grateful with some help to solve this problem.
I don’t understand, should the API return an array? If it returns an object even, it makes no sense to use the map as it is only an element that will be listed, you can access the properties directly (the key would always be 0).
– Giuliana Bezerra
Now that I touched that, I was in the head that everything that was printed in the browser would have to go through the map. Thank you very much!
– Thales Maia