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
3 Respostas
+ 5
Show your code first.
+ 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.
+ 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>
)
}