-1

In my React project, I'm trying to set different icons for each item based on their existence in an array which I get from local storage.

table.js

import React from 'react';
import isMovieInFavorites from './favorites';

class Table extends React.Component {
  constructor(props){
    super(props);
    this.state = {
        movies: [],
        //other state vars
    }
  }

  //some other codes
  render(){
      return (
        <div className="table-container">
          <table>
            {this.state.movies.map((row) => (
              <tr key={row.id}>
                <td>{row.title}</td>
                <td className="icon"><i className={(isMovieInFavorites(row.id) ? "fas" : "far") + " fa-star"}></i></td>
              </tr>
            ))}
          </table>
        </div>
      );
  }
}

I'm trying to change classname between fas and far based on isMovieInFavorites(id) from

favorites.js

function isMovieInFavorites(id){
  let movieArray = localStorage.getItem('faveMovieList') ? JSON.parse(localStorage.getItem('faveMovieList')) : [];
  movieArray.forEach((movie)=>{
    if(movie.id === id)
      return true;
  });
  return false;
}

I guess I'm doing fine with this part:

{(isMovieInFavorites(row.id) ? "fas" : "far") + " fa-star"}

Cause the condition works well if I check the results in console.log (inside favorites.js). Also if I do something like {(row.id == 10 ? "fas" : "far") + " fa-star"}, it works fine. But calling the function and checking the result somehow doesn't work and always will apply class far even the result is true.

What am I missing here? Is it wrong to call a function in this situation?

export default isMovieInFavorites;

Ghasem
  • 14,455
  • 21
  • 138
  • 171

1 Answers1

4

Here problem is with your function, forEach doesn't return anything out of callback, so the function will always return false

function isMovieInFavorites(id){
  let movieArray = localStorage.getItem('faveMovieList') ? JSON.parse(localStorage.getItem('faveMovieList')) : [];
  movieArray.forEach((movie)=>{
    if(movie.id === id)
      return true;
  });
  return false;
}

You need to use some or simple for loop instead

function isMovieInFavorites(id){
  let movieArray = localStorage.getItem('faveMovieList') ? JSON.parse(localStorage.getItem('faveMovieList')) : [];
  return movieArray.some(movie => movie.id === id)
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • 1
    Use array.some instead of the forEach. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some – Dov Rine Aug 25 '19 at 07:26