Shrey Srivastav
Shrey Srivastav

Reputation: 26

React Function call not working when mapped in JSX

I've created a function which finds a JSON data in React and it's working (I checked using console.log), but when I map in div using JSX ({myFunction.map()}) it doesn't show any output at all. I've tried using console.log in that section it's not working either.

States:

  const [coins, setCoins] = useState([]);
  const [search, setSearch] = useState("");

Here is the get request:

  useEffect(() => {
    axios.get(
      "secret-url"
    ).then((res) => {
      setCoins(res.data);
      console.log(res.data);  **//This cosole.log working, showing all json data**
    }).catch((error) => {
      console.log(error);
    });
  }, []);

Here is function:

  const filteredCoins = coins.filter((coin) => {
    coin.name.toLowerCase().includes(search.toLowerCase());
    console.log('ABCD'); **// This is working, meaning function is working**
  });

JSX Mapping (This Part is not working:

<div className="crypto-app">
  {filteredCoins.map(coin => { 
    console.log('ABCD'); **//Not Working**
    return <Coin key={coin.id} name={coin.name} price={coin.current_price} image={coin.image} volume= 
    {coin.volume} symbol={coin.market_cap} /> })}
</div>

Upvotes: 1

Views: 49

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 1

Try this code.

<div className="crypto-app">
   {coins
    .filter((coin) => {`enter code here`
     if (search === "") {
       return coin;
     } else if (
        Object.values(coin)
        .toString()
        .includes(search.toLowerCase())
        ) {
         return coin;
       }
     })
      .map(coin => { 
      console.log('ABCD'); **//Not Working**
      return <Coin key={coin.id} name={coin.name} price={coin.current_price} image= 
      {coin.image} volume= {coin.volume} symbol={coin.market_cap} /> 
     }) 
</div>

Upvotes: 0

Quentin
Quentin

Reputation: 943579

filter creates a new array containing all the values from the original array for which the function returns true.

Your function has no return statement so it always returns undefined so filteredCoins is empty.

You then map over the empty array so the mapping function never gets called (if it did, it would error because you misspelt console).

Upvotes: 2

Related Questions