Seems easy but I can't figure it out, how would you return the results from a function that's being imported to a component? I get the correct results when i console log them from the .then() but can't seem to return them to the component.
example:
functions.js
export const getFeatures = (e) => {
let features = Client.getEntries({
content_type: '###',
'fields.type': `${e}`
})
.then(response => {
return response.items;
})
.catch(console.error)
}
Component.js
import {getFeatures} from './functions.js'
const App = () => {
let x = getFeatures('home');
console.log(x)
return ( ... )
// expecting the array response [{},{},{}, .. etc], but getting undefined instead
}
getFeatures doesn't return anything, you should change it to return its promise:
export const getFeatures = (e) => {
return Client.getEntries({
content_type: '###',
'fields.type': `${e}`
})
.then(response => {
return response.items;
})
.catch(console.error)
}
then at App add a features state, that will get updated when you call getFeatures on mount stage called by useEffect:
import { useState, useEffect } from 'react'
import {getFeatures} from './functions.js'
const App = () => {
// create a features state
const [features, setFeatures] = useState([])
// on mount call 'getFeatures'
useEffect(() => {
getFeatures('home')
.then(setFeatures) // chain returned promise and pass setFeatures to update features
}, []) // add empty array to tell to run the code on mount only
// do some mapping with features, this is for example purpose
// remember to add an unique key to each feature
return ( features.map(feature => {
return <div key={feature.id}>{feature.name}: {feature.realease}</div>
}))
}
getFeatures('home') will return undefined instead of response.items in your code.
Try this:
// functions.js
export const getFeatures = async (e) => {
const resp = await Client.getEntries({
content_type: '###',
'fields.type': `${e}`
})
return resp.items;
}
// App.js
import {getFeatures} from './functions.js'
const App = () => {
getFeatures('home').then(x => {
console.log(x);
// do something else
});
return ( ... )
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With