Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
Create list in reactjs from nested arrays

I am trying to make a list of results from the Wikipedia API but I can only render the first element from the array.

here is a response example and my code :

["dog",["Dog","Dog meat","Dogecoin","Dogs in warfare","Dog breed","Dog training","Dog tag","Doggystyle","Doge's Palace","Dog Day Afternoon"],["","","","","","","","","",""],["https://en.wikipedia.org/wiki/Dog","https://en.wikipedia.org/wiki/Dog_meat","https://en.wikipedia.org/wiki/Dogecoin","https://en.wikipedia.org/wiki/Dogs_in_warfare","https://en.wikipedia.org/wiki/Dog_breed","https://en.wikipedia.org/wiki/Dog_training","https://en.wikipedia.org/wiki/Dog_tag","https://en.wikipedia.org/wiki/Doggystyle","https://en.wikipedia.org/wiki/Doge%27s_Palace","https://en.wikipedia.org/wiki/Dog_Day_Afternoon"]]

fetchingData() {
    if (this.state.query === ''){
      this.setState({result: []})
    } else {
    const url = 'https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=' + this.state.query;
    axios.get(url)
    .then(res => 
          this.setState({result: [res.data]}))
    }
  }

<div>
    {this.state.result.map(function(item, index){
      return(
        <ul>
          <li><a href={item[3][index]} target="_blank" key={index}>{item[1][index]}</a></li>
          </ul>
      )
    })}
      </div>

Any idea on how I can show a list of all the results?
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Dont wrap your res.data inside an array. Just make it {result: res.data}

about 4 years ago · Juan Pablo Isaza Relatório

0

import React from "react";
import { render } from "react-dom";
import axios from "axios";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      result: [],
      query: ""
    };
    this.handleChange = this.handleChange.bind(this);
    this.fetchingData = this.fetchingData.bind(this);
  }

  handleChange(e) {
    this.setState({ query: e.target.value });
  }

  fetchingData() {
    if (this.state.query === "") {
      this.setState({ result: [] });
    } else {
      const url =
        "https://en.wikipedia.org/w/api.php?action=opensearch&origin=*&search=" +
        this.state.query;
      axios.get(url).then((res) => this.setState({ result: res.data }));
    }
  }

  componentDidMount() {
    this.fetchingData();
    setTimeout(() => {}, 200);
  }

  render() {
    const key = this.state.result[1]; // name
    const value = this.state.result[3]; // link

    const mergedResults = key && key.map(function (x, i) {
      return { result: x, link: value[i] };
    })

    return (
      <div id="main">
        <input
          id="input"
          placeholder="search"
          value={this.state.query}
          onChange={this.handleChange}
        ></input>
        <button id="search" onClick={this.fetchingData}>
          Search
        </button>
        <div>
          <ul>
            {mergedResults && mergedResults.map((item, i) => (
              <li key={i}>
                <a href={item.link}>{item.result}</a>
              </li>
            ))}
          </ul>
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

here is my solution, live working example here https://codesandbox.io/s/react-basic-class-component-forked-s0qoe

code explanation - I just map result arrays 1 and 3 here

 const key = this.state.result[1]; // name
 const value = this.state.result[3]; // link

 const mergedResults = key && key.map(function (x, i) {
    return { result: x, link: value[i] };
 })

then map it

<ul>
   {mergedResults && mergedResults.map((item, i) => (
     <li key={i}>
        <a href={item.link}>{item.result}</a>
     </li>
    ))}
</ul>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda