I have following code import React from 'react' import { useEffect, useState } from…
- User
I have following code import React from 'react' import { useEffect, useState } from 'react' import Axios from 'axios'; import Dropdown from 'react-dropdown'; import {HiSwitchHorizontal} from 'react-icons/hi'; import 'react-dropdown/style.css'; import './currency.scss';
const CurrencyConverter = () => { const [info, setInfo] = useState([]); const [input, setInput] = useState(0); const [from,setFrom] = useState("usd"); const [to, setTo] = useState("inr"); const [options, setOptions] = useState([]); const [output, setOutput] = useState(0);
useEffect(() => { Axios.get( 'https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${from}.json` ) .then((res) => { setInfo(res.data[from]); }) }, [info]) // Function to convert the currency function convert() { var rate =info[to]; setOutput(input *rate); }return ( CurrencyConverter.component ) } I have a problem with info[to] - I've got error "Element implicity has an 'any' type because of expression is not of type 'number' . How can I solve this?
- Assistant
To solve the error "Element implicity has an 'any' type because the expression is not of type 'number'", you can add a type assertion to ensure that the value you are accessing is of type 'number'. Here's how you can modify your code:
Replace:
var rate = info[to];With:
var rate = info[to] as number;This will tell TypeScript that you are asserting the value of
info[to]to be of typenumber, resolving the error. - User
doesn't help me
- Assistant
Apologies for the confusion. The issue might be with the initial state of the
infovariable. When the component is initially rendered,infois an empty array, and accessinginfo[to]will result in an error because arrays do not have string indexes.To fix this issue, you can change the initial state of
infoto an object instead of an array. Here's the updated code:import React, { useEffect, useState } from 'react'; import Axios from 'axios'; import Dropdown from 'react-dropdown'; import { HiSwitchHorizontal } from 'react-icons/hi'; import 'react-dropdown/style.css'; import './currency.scss'; const CurrencyConverter = () => { const [info, setInfo] = useState({}); const [input, setInput] = useState(0); const [from, setFrom] = useState('usd'); const [to, setTo] = useState('inr'); const [options, setOptions] = useState([]); const [output, setOutput] = useState(0); useEffect(() => { Axios.get( `https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api@1/latest/currencies/${from}.json` ).then((res) => { setInfo(res.data[from]); }); }, [from]); // Function to convert the currency function convert() { var rate = info[to]; setOutput(input * rate); } return ( <div>CurrencyConverter.component</div> ); };
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.