lydal
lydal

Reputation: 940

Splitting an array of info to send request and receive info properly React JavaScript

I want to receive some info from an api using some ids and then saving the info to use later :

function useJobs () {
 const [tags, setTags] = React.useState({})
  React.useEffect(() => {
    async function fetchTags () {
      const tPromises = []
      for (const job of jobs) {
        console.log(job.tags)
        tPromises.push(fetchJSON(`/api/jobs/view-tag/${job.tags}`, { 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]
}

function useJobs () {
const [jobs, locations, departments, tags] = useJobs()
......
{tags[job.id] && <Col key={tags[job.id].id}>Tags:{tags[job.id].name} </Col>}

but since job.tags is an array instead of a single string I cant send my request properly and I receive an error like this:

"GET /api/jobs/view-tag/10,12,13 HTTP/1.1" 404 7681

how can I split the job.tags array into its individual parts and send requests for each one of them and receive their info?

this is my job.tags arrays (I have 3 job objects and inside the arrays, there are tag ids that need to be sent for each job)

this is the job.tags arrays and I have 3 job objects

Upvotes: 1

Views: 320

Answers (2)

Yousaf
Yousaf

Reputation: 29282

You need to iterate over each job.tags array and send the individual tag id in the request

You also don't need a then block inside the loop. Promise.All will resolve the promises after all promises have been pushed in the tPromises array

for (const job of jobs) {
   for (const tagId of job.tag) {

       tPromises.push(fetchJSON(`/api/jobs/view-tag/${tagId}`, {headers: headers})

   }
}

const dData = await Promise.all(tPromises)
console.log(dData)

Upvotes: 1

Lokesh
Lokesh

Reputation: 301

try this:

for (const job of jobs) {
  for (const tag of job.tag) {
    console.log(tag)
    tPromises.push(fetchJSON(`/api/jobs/view-tag/${tag}`, { headers: headers })
      .then((tags) => {
        return { [job.id]: tags }
    }))
  }
}

Upvotes: 1

Related Questions