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

308
Visualizações
React JS + AXIOS - How can I update the API results on click?

Can someone please help on updating the response data on click of list item. So there is a list of products being binded in <li>. When the user clicks on any of the list item, the value will be added as a keyword in API and data will be rendered accordingly

class SearchFilter extends Component {
      constructor(props) {
        super(props);
        this.state = {
          sidefilterbyProductData: [],
          sidefiltersbyContentType: [],
          featuredData: [],
          resourceData: [],
          othersData: [],
          error: false,
        };
      }
    
      componentDidMount() {
     
        axios
          .getAll()
          .then((response) => {
            this.setState({
              sidefilterbyProductData: response.data.data.filter_by[1].input_list,
              sidefiltersbyContentType: response.data.data.filter_by[0].input_list,
              featuredData: response.data.data.primary_data,
              resourceData: response.data.data.resources,
              othersData: response.data.data.others,
            });
          })
          .catch((error) => {
            this.setState({
              error: true,
            });
          });
      }
    
      handleonClick = () => {
      
        axios.get(`${this.key}`)
        .then((response) => {
          this.setState({
            featuredData: response.data.data.primary_data,
            resourceData: response.data.data.resources,
            othersData: response.data.data.others,
          });
        })
        .catch((error) => {
          this.setState({
            error: true,
          });
        });
      }
    
    
    
    
     render() {
        return <div><h3>Filter by product</h3>
                  <ul>
                    {Object.keys(this.state.sidefilterbyProductData).map((key, i) => (
                     <li key={key}><a onClick={this.handleonClick()}>{this.state.sidefilterbyProductData[key]}</a></li>
                    ))}
                  </ul></div>;
      }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

First, it's not clearly what is your problem, if is about a logic to implement it, or, it's a bug or something else...be welcome to complement your question if you want.

So, let's go.

I usually don't work components like this as class components, however, analyzing your code, you could add a parameter on handleonClick function, something like:

class SearchFilter extends Component {
    constructor(props) {
        super(props);
        this.state = {
            sidefilterbyProductData: [],
            sidefiltersbyContentType: [],
            featuredData: [],
            resourceData: [],
            othersData: [],
            error: false,
        };
    }

    componentDidMount() {
        // Is it needed ?
    }

    searchInApi = async (search:string): Promise<Foo[]> => {
        const response = await axios.get("/api/v1/products", {
            withCredentials: true,
            params: [
                'search' : search
            ]
        });
        
        return response.data;
    }

    handleonClick = (search:string): => {
        searchInApi(search)
        .then((response) => {
            this.setState({
                featuredData: response.data.data.primary_data,
                resourceData: response.data.data.resources,
                othersData: response.data.data.others,
            });
        })
        .catch((error) => {
            this.setState({
                error: true,
            });
        });
    }

    render() {
        return (
            <div>
            <h3>Filter by product</h3>
            <ul>
                {Object.keys(this.state.sidefilterbyProductData).map((key, i) => (
                    <li key={key}><a onClick={this.handleonClick()}>{this.state.sidefilterbyProductData[key]}</a></li>
                ))}
            </ul>
            </div>
        );
    }
}

You can separate responsibilities dividing your code into two components, one will contain the search in API logic and the other one that will render your front-end components.

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