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

99
Visualizações
Capitalize the data in react after fetching it using axios.get

I am trying to capitalize the product name after fetching if from a products list using a button.

Basically, a button fetches the data. Which gives us the product name as a heading with a CLEAR and CAPITALIZE button with each item.

Clear button removes the item from the list. Implemented. Capitalize button Capitalizes the product name.

Not able to figure out how to implement the capitalize function.

CODE::

capHandler function implements the functionality.

import React, { useRef, useState } from 'react';
import axios from 'axios';

function App(){
  const url = 'https://course-api.com/react-store-products';

  const [products, setProducts] = useState([]);
  const productNameRef = useRef();

  const fetchData = async () => {
    const { data } = await axios.get(url);
    setProducts(data);
  };

  const clearProducts = () => {
    setProducts([]);
  };

  const clearSingleProduct = (productID) => {
    const filteredArray = products.filter((item) => item.id != productID);
    setProducts(filteredArray);
  };

  function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }

  function capHandler() {
    console.log('Single Word Capitalized');
  }

  return (
    <>
      <button onClick={fetchData}>Fetch Products</button>
      <button onClick={clearProducts}>Clear Products</button>
      <div>
        {products.map((product) => {
          return (
            <div ref={productNameRef} id={product.id} key={product.id}>
              <h3 className="productName">{product.name}</h3>
              <button onClick={() => clearSingleProduct(product.id)}>
                Clear
              </button>
              <button onClick={capHandler}>Capitalize</button>
            </div>
          );
        })}
      </div>
    </>
  );
};

export default App;

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

Update the capHandler() function with the following body:

function capHandler() {
    setProducts(products.map(i => ({...i , name: capitalizeFirstLetter(i.name)}))
  }
about 4 years ago · Santiago Gelvez Relatório

0

you make the capHandler accept product index id and update the state.

 function capHandler(id) {
    const newProducts  = [...products]
    newProducts[i].name = capitalizeFirstLetter(newProducts[i].name)
    setProducts([...newProducts]);
 }

Also need to pass the map index while mapping the products

 <div>
 {products.map((product, i) => {
      return (
       ...

Lastly call the fucntion in the button

<button onClick={() => capHandler(i)}>Capitalize</button>
about 4 years ago · Santiago Gelvez 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