usama7365 / developer-community

community site soon❤️
25 stars 0 forks source link

i want to update the redis data #4

Closed Zainali005 closed 2 months ago

Zainali005 commented 3 months ago

i have redis data in my db (imageUrl,uuid,variant,sticker-sheet,status,type,size,price,userId,sku) i have call the api for fetch data in frontend and display in my frontend there is a form which contains name and description when user add name and description i want to update the redis data and my redis data is in hashes . How to do this

api: import { client } from "@/lib/redis"; import { NextRequest, NextResponse } from "next/server"; import { v4 as uuidv4 } from "uuid";

export async function POST(req: NextRequest) { try { if (req.method !== "POST") { return NextResponse.json( { status: 405, message: "Method not allowed" }, { status: 405 } ); }

const body = await req.json();
const uuid = uuidv4();
const cookies = req.cookies;
const userId = cookies.get("userId");

if (!userId) {
  return NextResponse.json(
    { status: 401, message: "Unauthorized" },
    { status: 401 }
  );
}

const productKey = `Product:${userId.value}:${uuid}`;

const dataToStore = { uuid, ...body };
const flattenedData: { [key: string]: any } = {};
for (const [key, value] of Object.entries(dataToStore)) {
  flattenedData[key] =
    typeof value === "object" ? JSON.stringify(value) : value;
}

await client.HSET(productKey, flattenedData);

return NextResponse.json(
  { status: 200, message: "Success" },
  { status: 200 }
);

} catch (error) { console.error("Error processing data:", error); return NextResponse.json( { status: 500, message: "Failed to process data" }, { status: 500 } ); } } Frontend:

"use client"; import { useEffect, useState } from "react"; import Image from "next/image"; import { usePathname } from "next/navigation"; import Shopify from "@/assets/shopify.png"; import { useSelector } from "react-redux"; import type { RootState } from "@/redux/store";

export default function Page() { const [dataStore, setDataStore] = useState<any[]>([]); const [product, setProduct] = useState<any | null>(null); const [userId, setUserId] = useState<string | null>(null); const [error, setError] = useState<string | null>(null); const [loading, setLoading] = useState(true); const [checkboxStates, setCheckboxStates] = useState<Record<string, boolean>>( {} ); const pathname = usePathname(); const { sku } = pathname; const selectedProduct = useSelector( (state: RootState) => state.products.selectedProduct ); const uuid = selectedProduct?.data?.uuid;

console.log(selectedProduct${userId}:${uuid}, "selected product rtk");

if (!selectedProduct) { return

No product selected

; } const handleCheckboxChange = (storeId: string) => { setCheckboxStates((prevStates) => ({ ...prevStates,

}));

}; useEffect(() => { const id = localStorage.getItem("userId"); setUserId(id);

async function fetchStores() {
  try {
    const response = await fetch("/api/get-stores");
    const data = await response.json();
    if (data.stores) {
      const filteredStores = data.stores.filter(
        (store: any) => store.userid === id
      );
      console.log("this is the filtered data store", filteredStores);
      setDataStore(filteredStores);
    } else {
      console.error("Stores data not found in response");
    }
  } catch (error) {
    console.error("Failed to fetch stores", error);
  }
}

fetchStores();

}, [userId]);

useEffect(() => { const fetchProduct = async () => { if (!sku) return;

  console.log("Fetching product with SKU:", sku);

  try {
    const response = await fetch(`/api/getSku?sku=${sku}`);
    if (!response.ok)
      throw new Error(`HTTP error! status: ${response.status}`);

    const data = await response.json();
    console.log("Fetched product data:", data);

    setProduct(data);
  } catch (error) {
    setError(error.message);
  } finally {
    setLoading(false);
  }
};

fetchProduct();

}, [sku]);

if (error) return

Error: {error}

; const handleSubmit = async () => { try { const updatedProduct = { ...product, title: (document.getElementById("title") as HTMLInputElement).value, description: ( document.getElementById("description") as HTMLTextAreaElement ).value, }; const response = await fetch( /api/products?userId=${userId}&uuid=${uuid}, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(updatedProduct), } );

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  console.log("Product updated successfully");
} catch (error) {
  setError(error.message);
}

}; return (

{selectedProduct.data.title

{selectedProduct.data.title || "Product Title"}

{selectedProduct.data.description || "Product Description"}

{selectedProduct.data.sku || "SKU ID"}