score:2
useeffect
runs after your component is mounted
which means rates
is just an empty array that doesn't have a property called rates
object.keys(rates.rates)
try to use
const [rates, setrates] = usestate({rates:[]});
or make a loading indicator for example
const ratescard = () => {
const [rates, setrates] = usestate([]);
useeffect(
()=>{
fetch("https://api.vatcomply.com/rates")
.then(ratesresponse => ratesresponse.json())
.then(rates => setrates(rates));
}
,[])
if(rates.length === 0) {
return <h1> loading </hi>
}
return (
<div classname="rates">
{object.keys(rates.rates).map(
rate => <button variant="outlined">
{rate}
</button>
)}
</div>
)
score:-1
first, your state is equal to []
in the first render you're trying to do the following: object.keys([].rates)
and obviously here rates
doesn't exist on the array
it ends up doing object.keys(undefined)
which results to the error.
so the solution to me is instead of setting the whole object to rates
you can just set the rates object of the response by destructuring (cf. https://developer.mozilla.org/en-us/docs/web/javascript/reference/operators/destructuring_assignment#object_destructuring):
useeffect(() => {
fetch('https://api.vatcomply.com/rates')
.then((ratesresponse) => ratesresponse.json())
.then(({ rates }) => setrates(rates));
}, []);
score:1
your default value for rates should be an empty object with rates
property set to an empty array ({rates: []}
).
by saying the following object.keys(rates.rates).map
you're going with the assumption that the rates
will be an object, and rates.rates
will be an array.
it works the "first" time due to how hot reloading works, because when you save your files, it injects codes to the browser and not remounting the entire app. thus, your app will continue from where it left off before, even if it crashed on the previous load..
change your state definition to the following: const [rates, setrates] = usestate({rates:[]});
this will ensure when your app tries to run object.keys(rates.rates).map
it doesn't crash because you have an array to iterate not null
/undefined
Source: stackoverflow.com
Related Query
- useEffect runs only once and after refresh it does not fetch again
- How to fetch data only once and never again in reacthooks and redux
- Fetch data only once to React App. Never fetch again after page reloads
- Why does data from my api only display once and when I refresh the page it gives an error
- Page does not refresh automatically after DELETE and UPDATE item on the lists. React-Redux
- componentdidmount does not empty the input field but only after page refresh it gets removed
- Why does my Auth.currentAuthenticatedUser() method return updated state after I reload and not when the useEffect's dependency runs (or login/logout)?
- window.Calendly.initInlineWidget is not defined on first load but works after refresh with useEffect in React and Gatsby
- Component not rendering after refresh , only after changing and saving the code
- Redux Saga does not work after any error. It totally stops working and need to refresh the page
- Redux Action only dispatched on refresh and not after redirect
- React useEffect but after set state value and only once
- ReactJS: how to call useEffect hook only once to fetch API data
- How to fetch data only once in a Next.js app and make it accesible to all the app, both in server and client
- React does not refresh after an update on the state (an array of objects)
- How to show Error or Validation messages only after form is submitted and not when user is typing in antd?
- Select control created in React does not reset on browser refresh (IE11 and Edge)
- Why does my React app append the external URL to http://localhost:/<port> and not to ONLY the URL itself?
- How to trigger useEffect in React only once AFTER some certain variable gets loaded
- React-Router push only changes the URL and does not navigate
- How do I fire React useEffect hook only once after state change?
- Why React component get re-rendered only once when state does not change?
- useEffect runs api request after I refresh the page
- How to run React useEffect only once and property update state with setState
- How can I call a useEffect only once after everything loads from redux useSelector hooks?
- React not redirecting after first login. But redirects after forcefully redirecting and doing a login action again
- In React useEffect does not update after the value has changed from other component
- React Router: The Router only loads / path and does not load any other path
- React-bootstrap-table - Expand component only after row click and not by default
- Is there a way to call useEffect only once and also have access to the current state of component?
More Query from same tag
- React useCallback does not get updated on state change
- React Bootstrap OverlayTrigger and Tooltip error
- why are my react components rendering in a horizontal direction instead of rendering vertically?
- reactjs: TypeError: Cannot read property 'from' of undefined
- Select input type in Reactjs
- Using jest-each for dynamic data testing
- JavaScript React, I can't read text file and assign a name
- Fetch Param from Route in Nav Bar, React-Router
- Laravel mix, webpack, terser - strip console log in production bundle
- How can I fix the positioning of this AccordionDetails using Material UI/Grid
- How to use react-navigation's withNavigation in typescript?
- Nodejs async loop is blocking React UI render
- React Router 4 - Component Remounting Instead of Re-Rendering
- Can't deploy smart contract application to Heroku
- React component using fetch not populating the state from response
- Checking authentication in React
- onChange access funtion not working in react js
- How to bind data from getJSON to ReactJS state
- Formik , how to reset dirty property
- React setState doesn't rerender on mobile only?
- React-Router V4 - Passing Props to Render function in Route Component to generate new component
- how can i convert an html/css/js website's Javascript into a react website?
- I am having problem to fetch limited records for two different "basic" or "premium" subscribers and show records count in pagination in ReactJS
- How do I set the background color of a styled div using a variable?
- How to redraw polygon using DrawingManager from "react-google-maps"
- Get id from post data react
- Is there a problem in 'react-metismenu-router-link' with react16?
- What approach can I use to wait for all child callbacks to complete?
- How do you test for the non-existence of an element using jest and react-testing-library?
- How to write and read real-time data from Firebase with React js