typeyes
typeyes

Reputation: 79

How to conditionally add values to array in React UseEffect with if else statement

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!

Upvotes: 0

Views: 624

Answers (1)

hazimdikenli
hazimdikenli

Reputation: 6019

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"
    }
  }
)

Upvotes: 1

Related Questions