It's me again!
I'm trying to make my life difficult.
I have two pages that both need data from an API call. So, instead of of using the dame function twice, I've moved the API request in a separate component. You may notice the weird res=>res.text ;it's not related to our current question.
export function GetListings(url) {
const [listings, setListings] = React.useState([])
**const [isLoading, setIsLoading] = React.useState(true)**
React.useEffect(() => {
fetch(url)
.then(res => res.text())
.then(text => {
setTimeout(() => {
setListings(JSON.parse(text))
setIsLoading(false)
}, 1500)
})
}, [])
return listings
}
This call does two things: fetches data AND sets isLoading state to false. THis is for a loader component, and is at the heart of my problem.
When I call the function on another page to get the data, I don't know how to receive the state isLoading change as well.
This is the component for the page that needs the data and the state
export default function FicheLogement() {
**const [isLoading, setIsLoading] = React.useState(true)**
const data = GetListings("../../data/logements.json")
**console.log(isLoading)**
(some code)
if (isLoading) {
return <Loader />
} else if (listing){
return (
<JSX...>
There, I'm declaring the same state, which is probably a mistake const [isLoading, setIsLoading] = React.useState(true) . Indeed, the console.log shows that the state does not update, and the loader loads forever. But I don't know how to receive the state change set in the API component.
I'm familiar with the concept of lifting state up, but have no idea how to implement it.
Thanks!