Home > Software engineering >  Property 'name' does not exist on type 'string'. How do I declare an object for
Property 'name' does not exist on type 'string'. How do I declare an object for

Time:09-21

I am trying to use axios to GET data from an API and display it in the view using hooks. I am getting a successful response from the API, but I don't know how to integrate type into the request. The API gives me back an object so that's how I want to declare my response variable (like the 'Gateway' interface below)

const Gateways: React.FC = () => {
  
 interface Gateway {
    id: number;
    name: string;
  }

  const [gateway, setGateway]  = useState('');

  const handleClick = async () => {
    axios.get("my/url")
      .then((response) =>
        setGateway(response.data)
      ).catch(error=>console.log(error));
  };

  return (
    <div className="content">
      <div>{ gateway.name }</div> //error is here: Property 'name' does not exist on type 'string'.
 )
};

export default Gateways;

Thank you!!

CodePudding user response:

Gateway is implicitly a string type (''), but later you treat it like an object

  const [gateway, setGateway]  = useState(''); // string type
 <div>{ gateway.name }</div>  // object type

You should consider :

   const [gateway, setGateway]  = useState<Gateway>({} as Gateway);

also, you are missing one closing div

CodePudding user response:

It takes time to populate the gateway, so normally we do

  if (!gateway) return null
  return (
    <div className="content">
      <div>{ gateway.name }</div>
    </div>
  )

CodePudding user response:

Please, checkout your content-type header in response. I think it maybe is text/plain.

If it is text/plain, consider using application/json instead, so axios can parse it for you.

However, if you can't change the content-type, use setGateway(JSON.parse(response.data)) to parse the response.data to a JSON object.

Also, start the state without any value and use gateway?.name where the state is used. If it's not loaded yet, you won't get the error.

CodePudding user response:

const [gateway, setGateway] = useState({});

You can either use above format or you can also pass default or initial properties . This will return an object gateway which is statefull.

  • Related