简体   繁体   中英

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;

Update the capHandler() function with the following body:

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM