Home > Software design >  Is there an easier way to map metod from react-js?
Is there an easier way to map metod from react-js?

Time:01-27

import React, { useEffect, useState } from "react";
import axios from "axios";
import "./style.scss";

function Product() {
  function dataget() {
    axios.get(`http://localhost:9999/users/`).then((res) => {
      setProducts(res.data);
    });
  }

  const deleteclick = (_id) => {
    axios.delete(`http://localhost:9999/users/${_id}`).then(() => {
      dataget();
    });
  };

  const [products, setProducts] = useState([]);
  const [search, setSearch] = useState("");
  useEffect(() => {
    dataget();
  }, []);

  function handleclickplus() {
    setProducts([
      ...products.sort((a, b) =>
        a.title > b.title ? 1 : b.title > a.title ? -1 : 0
      ),
    ]);
  }
  function handleclickminus() {
    setProducts([
      ...products.sort((a, b) =>
        b.title > a.title ? 1 : a.title > b.title ? -1 : 0
      ),
    ]);
  }

  return (
    <div>
      <button onClick={() => { handleclickminus(); }}>Çoxdan aza</button>
      <button onClick={() => { handleclickplus(); }}>Coxdan aza</button>
      <input type={"text"} placeholder="search" onChange={(e) => { setSearch(e.target.value); }} />
      {products
        .filter((products) =>
          products.title.toLowerCase().includes(search.toLowerCase()))
        .map((element) => {
          return (
            <>
              <img src={element.imageUrl} alt="" />
              <h1>{element.description}</h1>
              <h1>{element.title}</h1>
              <h1>${element.price}</h1>
              <button onClick={() => { deleteclick(element._id); }}> delete</button>
            </>
          );
        })}
    </div>
  );
}

export default Product;


I tried to make the code more memorable and shorter in my writing, but I couldn't achieve exactly what I wanted.

I'm working on a react app and using useState to create a state, which will be sent via props and the sendData function (which updates state via props in the parent component). It works right now, but seems very unelegant/just plain bad.

CodePudding user response:

There are a couple things to improve performance.

  1. Make the inner component you are mapping a component itself, helps prevent rerenders when not needed.

  2. memoize the filter map function so it doesnt need to run every render cycle. or create a useEffect that watched for search item changes and then reruns the filter map only then.

  3. abstract away the date fetches into another "thing" maybe try jotai or recoil to hold your data.

  4. conventions in JS should be camelCasing for variables ex: deleteClick vs deleteclick

  5. onClick function calls cal just pass a function, cleans things up a bit

    onClick={handleClickMinus}

CodePudding user response:

I'm not sure about your mean about "map metod (or method)". But based on your code, I have some recommendations for you to optimize it, maybe it will help your code become more memorable.

Firstly, you may create a new component to render the product card. It will help your code be shorter and easier to read.

function ProductCard({ product, deleteProduct }) {
  return (
   <>
      <img src={product.imageUrl} alt="" />
      <h1>{product.description}</h1>
      <h1>{product.title}</h1>
      <h1>${product.price}</h1>
      <button onClick={() => { deleteProduct(product._id); }}> delete</button>
    </>
  )
}

We may update the Product list part to:

{products
   .filter((products) =>
      products.title.toLowerCase().includes(search.toLowerCase()))
   .map((product) => {
          return (
            <ProductCard 
              product={product}
              deleteProduct={(id) => deleteclick(id)}

          );
        })}

Second, you may memoize a filter map function in your component instead of call it every time.

Third, you may move the axios call to another JS file as a service and call it in your component.

Last, I think you can make a function with a parameter maybe sorter to handle both of function handleclickplus and handleclickminus.

  • Related