I've been struggling to grasp the concept of Promises/then-ables for a while now. Currently, I am working with NextJS.
My goal is to chain together the following steps:
- Retrieve data from an API
- Save the data
- Modify the data to create a component (without causing an infinite loop)
I'm facing difficulty in obtaining the correct data for step #3. Despite trying different approaches, I seem to be stuck at this stage.
For this purpose, I am utilizing the useEffect hook, although I acknowledge there might be alternative methods available as well: https://nextjs.org/docs/basic-features/data-fetching/client-side
export default function Survey() {
const [dataDB, setDataDB] = useState('');
let roles;
function createCards(rolesArr) {
let role1 = tabs.find(x => x.id == rolesArr[0])
let role2 = tabs.find(x => x.id == rolesArr[1])
let role3 = tabs.find(x => x.id == rolesArr[2])
// the above is null
// the below is also null:
// let role1 = tabs.find(x => x.id == dataDB[0])
roles.push(role1)
roles.push(role2);
roles.push(role3); // component will map over these 3
}
useEffect(() => {
fetch('example.com/api')
.then((response) => response.json()) // 1. Retrieves an array like [0, 3, 5]
.then((data) => {
setData(dataDB) // 2. Utilizing hook to setData, data will be stored in the database later
}
.then((rolesArr) => createCards(rolesArr)) // 3. Modifying data for the component
})
)
return (
{
roles.map((path) => (
<Card key={path.id}>
<Text>{path.title}</Text>
</Card>
))
}
)
}