score:0
the usage of useeffect
hook notifies react that component has to perform some side-effects(passed as a callback function to the hook) after it has been rendered, the default behavior of useeffect
will run both after the first render and after every update, but when an empty array is passed as a dependency the side-effect will be performed only once after the component has been mounted for the first time.
in the case above useeffect(hook, [])
the callback hook will be called after the component has mounted for the first time, which means the component will render with the initial state on it's first render which is an empty array ([]
).
that is why when you try to access countries[1].name
it errors out, because the value of countries
is still an empty array on the first render.
const [ countries, setcountries ] = usestate([])
const hook = () => {
axios
.get('https://restcountries.eu/rest/v2/all')
.then(response => {
setcountries(response.data)
})
}
useeffect(hook, [])
// can not use index expression to get the first element because
// the value of countries is still an empty array on first render
// it only gets populated when axios.get call is succesful inside the
// callback in useeffect hook after the component has mounted for the first time
console.log(countries[1].name)
solution
check for the length
of the array before trying to get the first element,
if (countries.length) {
console.log(countries[1].name)
}
p.s.- you should be using a .catch
block for handling the error when the api call fails.
score:0
there is an example solution for a type of request like this in the react document:
https://reactjs.org/docs/hooks-effect.html
the hooks provided by react are for the most part, asynchronous functions provided by react, to help manage the loading of data, presenting it to the dom, and dealing with updates. the useeffect
behaves in a similar way to componenthasloaded
, where the hook is triggered once the functional component has rendered, and the dom has been loaded, but it may not have been presented to the user yet. it's important to remember this when working with useeffect
. usestate
is another asynchronous hook, but it provides access to the state property of the hook after it has been instantiated, and won't immediately trigger a re-render of the component, unless the data is updated.
the reason you get an undefined
error when you attempt to access console.log(countries[1].name)
is because the array at that point is still empty.
i'll explain in code:
const mycomponent = () => {
// initialise countries: []
const [ countries, setcountries ] = usestate([])
const hook = () => {
axios
.get('https://restcountries.eu/rest/v2/all')
.then(response => {
// this is allow you to see the dom change after the effect has run
settimeout(() => setcountries(response.data), 5000);
})
}
// tell react to run useeffect once the component is loaded
useeffect(hook, [])
// display data
return (
<p>countries: {countries.length}<p>
);
};
because useeffect
is an asynchronous function, it doesn't block the execution of the function and the rendering of the dom, but refreshes the dom once useeffect
is completed. in this case, you are setting the country list, based on the result of the useeffect function.
the useeffect
function will still trigger, you will have access to the state, and the function will re-render when the state is updated.
see codepen example:
score:1
coz you can loop through the empty array, but you can't access the index which is not available yet
// so if
countries = []
// this will not throw error
{countries.map(country => (
<li>{country.name}</li>
))}
// but this will
console.log(countries[1].name)
// if you want to check try to run this
console.log(countries.length ? countries[1].name : "not available yer");
Source: stackoverflow.com
Related Query
- Explanation needed: getting data from API with useEffect hook and get name
- react get data from rest api with axios and and useEffect redering empty array plus array with data
- Problems with getting data from API in React-redux and Redux-Thunk
- Not getting data from api into the web page, can anyone help me through this where I am getting an error and what can i do to get data
- React error when trying to get data from api using useEffect hook
- how to get spesific data from api with axios and react js?
- Getting data from firebase with axios and useEffect
- React.js: loading JSON data with Fetch API and props from object array
- How to use useEffect hook properly with array dependency. I passed state from redux store and still my component renders infinitely
- React Hook useEffect : fetch data using axios with async await .api calling continuous the same api
- React Context : Get Data from API and call API whenever some events happens in React Component
- ReactJS: get data from api and map data
- How to make the Service Worker cache data from API and update the cache when needed
- Delete data from API with Axios and ReactJS
- how to set an useEffect to fetch data from API at first render with eslint-react-hooks?
- I get data from Api but when I try to set the value with useState it give me an empty object
- Fill context from REST API and use it in a React component with useEffect and useContext
- get data from multiple react child and send into one API
- select option from dropdown using API and get that selected value but i am getting last value which i have not selected in react
- use axios with react to get data from api
- Why do I get an array of promises when getting data from the blockchain with useEffect?
- How to pass variable to graphql from method when onClick with button and get it's return data back?
- How to fetch data from a custom React hook (API) with onClick and display it in a Div using TypeScript?
- Unable to access/manipulate data from weather API using axios with useEffect in React.js
- How to load and display data with React from an API running on localhost
- Post Data With Redux and Fetch API with Axios Get Error Result so Looping Response Pending
- Getting object data from API and then displaying it (React Fetch)
- i was trying to map data from api to some jsx element and i keep getting type error
- Using usestate hook with array when getting data from redux store
- Display data from API using react component and useEffect
More Query from same tag
- React "export default" stateless component issue
- Webpack Can't Resolve React Components
- React-Bootstrap-Typeahead: Clear on Menu Selection
- React - pixel ratio - set 2x 3x images for retina devices
- React select multi select one option not clearable
- react-bootstrap-typeahead TypeScript- Ref - getInstance does not exist
- How to fix Uncaught TypeError: Cannot read property 'getState' of undefined?
- ReactJs - Not able to map data to table rows and columns
- trying to set the state of react-highcharts, but it isn't working?
- Passing data from child to parent and setting state
- How to call setTimeOut on a component class
- Chart works uncorrectly chart.js
- Redux React create initial state from API
- unable to load marker in react leaflet next.js
- edit text input React
- How can I get the current map center coordinates using getCenter in @react-google-maps/api?
- How to make payments with stripe in a django and react app?
- Gulp watch task does't exit on Ctrl C
- How to fix "TypeError: items.map is not a function" when working with React and APIs?
- Parse Error:Adjacent JSX elements must be wrapped in an enclosing tag(React.js )
- Why is component not having props?
- What do curly braces around a variable in a function parameter mean
- Is there a way to utilize React's `history.push()` to trigger a file download?
- I have a react problem that is driving me crazy
- React Typescript - Change default loaded component
- Argument of type 'void' is not assignable to parameter of type 'SetStateAction | undefined'
- Accessing this.props function in react ComponentDidMount
- React - Link redirect to item but not refresh the component
- How Insert data to two tables at once?
- How can i add class to a image element in quill image Handler?