Regarding fetch api in react js | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Regarding fetch api in react js

I am building a project in react js in which I have used api.. After fetching data, first it return undefined and then it gives required data.. Why is this happening.. And what is the solution to prevent this..!! I am not using axios

14th Aug 2020, 6:01 AM
Bhuvanesh
Bhuvanesh - avatar
3 Answers
+ 5
Show your code first.
14th Aug 2020, 6:15 AM
Rowsej
Rowsej - avatar
+ 3
Since no code is provided, I hope this could be possible reason. considering class based component, if you are using side effects in componentDidMount data will be undefined on initial render since the render method runs before componentDidMount. So to stop this behaviour, u need a loading state, initially set to true, and in the fetch api then promise set loading state to false, And in render method try to show some loader if loading is true else render the component.
14th Aug 2020, 6:53 AM
Мг. Кнап🌠
Мг. Кнап🌠 - avatar
+ 2
Use conditional on jsx to ensure only display ready fetched data. eg. function App () { // fetch fetchedData from api here using lifecycle methods here // : return ( <div> { fetchedData ? <p>fetchedData</p>: null } </div> ) }
15th Aug 2020, 4:29 AM
Calviղ
Calviղ - avatar