I'm trying to make an api call to retrieve some data:
index.js
const [companyInfo, setCompanyInfo] = useState({})
useEffect(() => {
getCompaniesInfo()
}, [])
getCompaniesInfo = async () => {
try {
const { data } = await axios({
method: 'GET',
url: `myURL/${companyID}/settings`,
headers: { Authorization: `Bearer ${user.token}` },
})
if (data) {
setCompanyInfo(data)
}
} catch (error) {
console.log(error)
}
}
return (
{componentSelected == 0 && <NewRequest companyInfo={companyInfo} />})
)}
const mapStateToProps = (state) => {
return {
companyID: state.auth.id,
user: state.auth,
}
}
export default connect(mapStateToProps)(Parent)
NewRequest.js
const NewRequest= ({ companyInfo }) => {
console.log('companyInfo', companyInfo.time.minuteInterval) // it should print a number, but it says Cannot read property 'minuteInterval' of undefined
return (
<DatePicker
minuteInterval={companyInfo.time.minuteInterval}
)
}
How can I do to use info that I recover from api in the parent also in the child?
CodePudding user response:
This is because NewRequest
at first render has not yet the result from the API call.
You can add another check when rendering NewRequest
to make sure it only render when it gets the result from API.
return (
{
componentSelected == 0 && companyInfo && companyInfo.time &&
<NewRequest companyInfo={companyInfo} />
}
)
CodePudding user response:
The problem is NewRequest is receiving an empty object on first render, you can avoid it by doing something like this
return (
{componentSelected == 0 && companyInfo?.time && <NewRequest companyInfo={companyInfo} />})
)}
I also suggest that you switch useState({}) to either useState(undefined) or some default values object
that way it will be easier to check for a truthy value before rendering or you could have some values to fall back to if the request fails