Ternary operator in Typescript based Reactjs does not work as I expected

Advertisements

I am newbie in TypeScript+ReactJS
In my code Ternary operator does not work as I expect.
This is my code:

import React, { SyntheticEvent,useRef,useState } from "react";
import Result from './Result';
//main application
const App:React.FC=()=>{
    const [searchResult,setSearchResultState]=useState<Array<Object>>([]);
    const setSearchResultFunc = (value:Array<Object>)=>{
        setSearchResultState(value);
    }

    return (
    <section id="App">
        <SearchPanel setResult={setSearchResultFunc}/>
        {
            (searchResult===[])
            ?""
            :<Result result={searchResult}/>}
        <footer className={searchResult===[]?"absolute":""}>
          <p>All data are received using Google Place API. {"result: " +searchResult}
          <br/>
          This website is not actual working website and is made just for educational purpose. 
          </p>
        </footer>
    </section>
    )
}
export default App;

interface searchProps{
    setResult:(value: Array<Object>) => void
}
const SearchPanel=({setResult}:searchProps)=>{
    const searchElementRef = useRef(null as any);
    const search =(e:SyntheticEvent)=>{
        const searchValue = searchElementRef.current.value;
        if(typeof searchValue!=="string"){
        alert("only text allowed");
    }else{
        //validate user search input
        regexValidate(searchValue)
        ?alert("No special characters are allowed")
        //send request to server if no special character is found
        :fetch("//localhost:3000/city?name="+searchValue,{
            method:'GET',
            credentials:'include',
            headers:{
                'Accept':'application/json',
                'Content-Type':'application/json'
            }
        }).then((data:any)=>{
            return data.json();
        }).then(data=>{
            setResult(Object.entries(data));
        })
    }
    e.preventDefault();
}
const regexValidate = (value:string)=>{
    const specialChars = /[`!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]/;
    return specialChars.test(value);
}
return(
    <section className="text-center absoluteCenter">
        <h1 className="text-white text-lg uppercase mb-5">Wanna travel somewhere?</h1>
        <form action="/" method="GET" onSubmit={e=>search(e)}>
            <input type="text" placeholder="SEARCH FOR CITY ex:London" ref={searchElementRef}/>
        </form>
    </section>
)
}

So, what I expect is, when application starts, the App component will have an empty Array state which is called searchResultFunc. And when user performs a search, it will update the state by calling function setResultState. The function will have data that search has returned and will alter previous state data to the new data.

According to this ternary operator,

{
        (searchResult===[])
        ?""
        :<Result result={searchResult}/>

}

I thought the page should not have Result component from beginning, but when I render the page for first time,

I already see Result in HTML inspector which means ternary operator does not work as I expected.

To check the value of state when the page renders for first time, I made such code

    <p>All data are received using Google Place API. {"result: " +searchResult}
    <br/>
    This website is not actual working website and is made just for educational purpose. 
    </p>

If state searchResult has some data, the webpage should show value of the state. However, the result state is empty.

What did I do wrong?

>Solution :

you need to change searchResult===[] to searchResult.length === 0

Leave a Reply Cancel reply