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

Time:07-11

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,

enter image description here

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. enter image description here

What did I do wrong?

CodePudding user response:

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

When you compare arrays using === you are actually checking whether the two arrays are the same array. It does not check whether the two arrays have the same content.

Here's a short program that illustrates the difference: https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgLhtATgSzAcwNoF0YC8MeAUKJLAEZKoY75GnnQzA1TpZ6Hwl-MgANgFMAdIJCYAFAHI4BApQD8MgDTwFlAJRlwEIWInS5C4CvXyCwHXyA

CodePudding user response:

You need to check whether array is empty or not. You can do the following.

arr=[]

arr.length === 0? True : False

arr===[] does not work as it checks the array reference whether both the array points toward same memory reference. Hence it will fail everytime even if elements are same in both array unless and until it's same array referenced.

  • Related