0

I wanted to pass code parameter in the URL of the src attribute of <img> in a react component. I have done the below implementation but it showing invalid src in console

import React, {useState,useEffect} from 'react';
import { Button } from 'react-bootstrap';

const TimeZoneComponent = () => {

const [data, setData] = useState([]);
const [city,setCity] = useState('');
const [printCity, setPrintCity] = useState(false);


const clickfn = () =>
{
    setPrintCity(true);
    if(printCity)
    {
        timeZone(city);
    }
}


async function timeZone(city) {
    await fetch(`http://worldtimeapi.org/api/timezone/Asia/${city}`)
    .then((response)=>response.json())
    .then((json)=>{
        //console.log(json);
        setData(json);
    })
}



useEffect(()=> {
        timeZone();
},[])

let mystr = JSON.stringify(data.datetime);

console.log("city typed  =  "+city);

const cityToCodeMatcher = (city) => {
    let code;
    if(city === "Kolkata") code='IN';
    else if(city === "Tokyo") code='JP';
    return code;
}

const readySRC = (city) => {
    let temp =  "https://www.countryflags.io/".concat(cityToCodeMatcher(city));
    return temp.concat("/shiny/64.png");
}



return(
    <>
    <div className="timezone">       
        <div id="timezone-input">
            <label>Type Asian City Here..
                <br/>
            <input type="text" placeholder=" Type city here.." onChange={(event)=>setCity(event.target.value)}/>
                <br/>
            <Button className="timezone-button" onClick={()=>clickfn()} >Get Current DateTime</Button>
            </label>
        </div>
        Date: {mystr?.slice(1,11)} <br/>
        Time: {mystr?.slice(12,20)} <br/>
        Timezone: {data.timezone}
        <div>
            //Here I want to pass parameter in src of<img>
            <img src={readySRC({city})} alt="Country flag"/>
            ///////////
        </div>
    </div>
    </>
);

}
export default TimeZoneComponent;

Do anyone help how to do so?

1
  • 1
    If you're using fetch with a then, there's no reason to use async await. Commented Aug 9, 2021 at 9:42

1 Answer 1

1
<img src={readySRC({city})} alt="Country flag"/>

readSRC({city}) means

readSRC({
   city: city
});

in your code should be

readSRC(city) 
Sign up to request clarification or add additional context in comments.

2 Comments

It works but I am getting delayed responses when I input city in the same code, do we have any way to speed up the API response of timeZone API.
@MohitMaroliyaB17CS036, Delayed response is just a network delay, your code has some other problem, img will always has wrong source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.