I receive some info from an API based on some ids. there are 3 job objects, each job has an array of tags and in each array, there are some ids that get sent to the API to return the tag info:
function useJobs () {
const [jobs, setJobs] = React.useState([])
const [locations, setLocations] = React.useState({})
const [departments, setDepartments] = React.useState({})
const [tags, setTags] = React.useState({})
React.useEffect(() => {
async function fetchTags () {
const tPromises = []
for (const job of jobs) {
for (const tag of job.tags) {
console.log(tag)
tPromises.push(fetchJSON(`/api/jobs/view-tag/${tag}`, { headers: headers })
.then((tags) => {
return { [job.id]: tags }
}))
}
}
const dData = await Promise.all(tPromises)
console.log(dData)
setTags(prev => Object.assign({}, ...dData))
}
fetchTags()
}, [jobs])
return [jobs, locations, departments, tags]
}
export default function Jobs () {
const [jobs, locations, departments, tags] = useJobs()
.....
{jobs.map(job => (
{tags[job.id] && <Col key={tags[job.id].id}>Tags:{tags[job.id].name} </Col>}
)}
....
}
the problem is that only one item from each array of tags for each job is printed. for example if the array is [1,2,3] and then gets converted to [Css,Js,HTML], only Css is shown. How can I fix this issue?
edit:
React.useEffect(() => {
async function fetchTags () {
const tPromises = []
for (const job of jobs) {
for (const tag of job.tags) {
console.log(tag)
tPromises.push(fetchJSON(`/api/jobs/view-tag/${tag}`, { headers: headers })
.then((tags) => {
return { [job.id]: tags }
}))
}
}
const dData = await Promise.all(tPromises)
const tags = dData.reduce((acc, item) => {
const [key, value] = Object.entries(item)
if (acc[key]) {
acc[key].push(value)
} else {
acc[key] = [value]
}
return acc
}, {})
setTags(prev => ({ ...prev, ...tags }))
console.log(dData)
setTags(prev => Object.assign({}, ...dData))
}
fetchTags()
}, [jobs])
return [jobs, locations, departments, tags]
}