Home > Software design >  React how to print not found in react js
React how to print not found in react js

Time:09-25

I have code where iam making post request to api and getting all the data from api in a table. And I am searching for a currency data with currency name if found i am printing the data in div if not found i want to print not found in the same div.

 import { useState,useEffect } from "react";
    import axios from "axios";
    function CurrencyInfo (){
        let [currData, setCurrData] = useState([])
        let [searchData, setSearchData] = useState([]);
    
        useEffect(()=>{
            axios.get("https://api.coinbase.com/v2/currencies").then((res)=>{
                setCurrData(res.data.data)
            })
         },[])
        let Search = (event) =>{
            event.preventDefault();
            let arr = []
            let toSearch = event.target.search.value;
           currData.map((val)=>{
               if(toSearch.toLowerCase() === val.name.toLowerCase()){
                arr.push(val.name,val.id,val.min_size)
                return setSearchData(arr)
               }
            })
    
        }
     return (
            <div>
                <form onSubmit={Search}>
                    <input type = "text" name="search"/><br/>
                    <input type= "submit" value="Search"  className="buttons"/>
                </form>
                {searchData.map((val)=>{
                     return <div>{val}<div id="not"></div></div> 
                     
                    })}
                    
             <table border="1">
                    <tr>
                        <th>Name</th>
                        <th>Id</th>
                        <th>Minimum value</th>
                    </tr>
                    {currData.map((val)=>{
                       return (
                                <tr>
                                <td>{val.name}</td>
                                <td>{val.id}</td>
                                <td>{val.min_size}</td>
                                </tr>
                            )
                       })}
                </table>
                
            </div>
        )
    }
    export default CurrencyInfo

CodePudding user response:

You can try this to resolve your issue (Assuming you have name parameter in currency) :

{searchData.map((val)=>{
        return <div>{val.name || 'not found'}</div>                      
    })}

CodePudding user response:

you can use conditional statement on search data array

searchData.length >= 0 ? (
{searchData.map((val)=>{ return <div>{val}</div> })}
) : ( return <div id="not">Data not found</div>)
  • Related