Home > OS >  Capitalize the data in react after fetching it using axios.get
Capitalize the data in react after fetching it using axios.get

Time:06-14

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;

CodePudding user response:

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

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

Lastly call the fucntion in the button

<button onClick={() => capHandler(i)}>Capitalize</button>

CodePudding user response:

try this

function capHandler() {
    setProducts(products.map(i => ({...i , name: capitalizeFirstLetter(i.name)}))
  }
  • Related