0

I am comparing two arrays. I am searching to see if values in 'products' array are present in the 'favorites' array. If they are present, I need to set new values in the 'products' array. This is something I need to do on the initial page load, so I am using useEffect. I am clearly doing something wrong with my if else statement that I have added to my useEffect.

Here is the code sandbox: https://codesandbox.io/s/goofy-wright-49286?file=/src/App.js

And the code:

import React, { useState, useEffect } from "react";
import axios from "axios";

export default function App() {
  const [favorites, setFavorites] = useState([]);
  const [products, setProducts] = useState([]);
  const [productsDisplay, setProductsDisplay] = useState([]);

  useEffect(() => {
    axios.get("./favorites.json").then((res) => {
      setFavorites(res.data.favorites);
    });
    axios.get("./products.json").then((res) => {
      setProducts(res.data.products);
    });
  }, []);

  /* Set Initial Products Display */
  useEffect(() => {
    setProductsDisplay(
      products.map((item) => ({
        if (favorites.find(({ slug }) => slug === item.slug)) {
          ...item,
          display_default: "block",
          display_added: "none"
        } else {
          ...item,
          display_default: "none",
          display_added: "block"
        }
      }))
    );
  }, [products]);

  return (
    <>
      {productsDisplay.map((product, i) => (
        <div key={i}>
          <p style={{ color: "red", display: product.display_default }}>
            {product.name}: Add to Favorites
          </p>
          <p style={{ color: "green", display: product.display_added }}>
            {product.name}: Added
          </p>
        </div>
      ))}
    </>
  );
}

Any help is greatly appreciated!

3
  • favorites also needs to be in the useEffect dependency. since the codesandbox is not really "working" due to api, cannot go further from here Commented Jan 25, 2022 at 18:49
  • when using map, make sure that you are returning the item from the iteratee function. This might be the reason. Commented Jan 25, 2022 at 18:53
  • probably just adding return for the new item should solve your problem. Commented Jan 25, 2022 at 18:57

1 Answer 1

1

You are not returning the item from the map function, try changing the handler to look something like;

products.map(item=> {
  if (favorites.find(f => f.slug === item.slug)){
    return {
      ...item,
      display_default: "block",
      display_added: "none"
    }}
    else return {
      ...item,
      display_default: "none",
      display_added: "block"
    }
  }
)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.