Home > database >  How can I map this join data in React JS
How can I map this join data in React JS

Time:05-05

I have two API Data I am using. I am trying to map the data as list item. I am also trying to map the correct logo for the correct item using productCode as a matching point. How can I achieve this? I have attached my code below. Each item must have the logo, the amount, and productCode. Please if there is also a better way to merge the two API, I would be happy to learn....

export default function App() {

  const [Alldata, setAlldata] = useState([]);
  useEffect(() => {
    // GET request using fetch inside useEffect React hook
    fetch("http://localhost:1337/api/rows/")
      .then((response) => response.json())
      .then((json) => setAlldata(json));
    // empty dependency array means this effect will only run once (like componentDidMount in classes)
  }, []);

  const token = "TOKEN HERE";
  const [result, setResult] = useState([]);

  useEffect(() => {
    fetch(
      "https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/product/",
      {
        method: "GET",
        headers: { Authorization: `Bearer ${token}` },
      }
    )
      .then((res) => res.json())
      .then((json) => setResult(json));
  }, []);

  const mainDATA = {result, Alldata};
  console.log(mainDATA);


  return (
    <div>App</div>
  )
}

CodePudding user response:

First up:

  useEffect(() => {
    setProducts(result.result);
  });

.. is likely to cause an infinite loop as it'll run on every render. Calling setProducts will queue a new render, that'll re-run useEffect etc, that'll queue a new render etc.

I think you can leave out this useEffect and simply use:

useEffect(() => {
    fetch(
      "https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/product/",
      {
        method: "GET",
        headers: { Authorization: `Bearer ${token}` },
      }
    )
      .then((res) => res.json())
      .then((json) => setProducts(json?.result));
  }, []);

.. to write direct to the products state.

Then (assuming that products is an array, and you have a component ProductItem that can render it) you'd write something like:

return (
<div>
{ products.map( product => <ProductItem key={product.id} product={product}/> ) }
</div>
  )
  • Related