skip to Main Content

I need to map through an array so i can get all the notes pushed in an array params.createdNotes can i map inside the variable sortNotes so i can have a url like below :

/api/35678&page=1&notes[]=2&notes[]=4&notes[]=5

params.createdNotes = [2, 4, 5]

instance.fetchNotes = (params) => {
    let sortNotes =  (params.createdNotes.length === 0) ? '' : '&notes[]='+params.createdNotes;
    return  instance.get(
        '/api/'+params.section+'&page='+params.currentPage+sortNotes
    )
}

2

Answers


  1. Use the built-in URLSearchParams API to take care of creating a valid querystring first. Then when we’re done, call toString to get the resulting querystring.

    const createdNotes = [2, 4, 5];
    
    const params = new URLSearchParams();
    
    createdNotes.forEach((note) => params.append("note[]", note));
    
    console.log(params.toString());

    In the context of your code:

    instance.fetchNotes = (params) => {
      const params = new URLSearchParams();
    
      params.set("section", params.section); // or whatever
      params.set("page", params.currentPage);
    
      // append params
      params.createdNotes.forEach((note) => params.append("notes[]", note));
    
      return instance.get(
        "/api/?" + params.toString() // now we're done, turn into querystring
      );
    };
    
    Login or Signup to reply.
  2. It looks like you’re trying to append a number of query strings for an unknown number of notes whose ids are stored in the array params.createdNotes, but you’re unsure how to map through them while adding the query string. You could try pulling those URL ids with a for…in loop and using template strings:

    let params = {};
    params.createdNotes = [2, 4, 5];
    params.section = "section";
    params.currentPage = 1;
    
    fetchNotes = createdNotes => {
      let sortNotes = `/api/${params.section}&page=${params.currentPage}`;
      for (let noteId in createdNotes) {
        sortNotes += (`&notes[]=${noteId}`);
        console.log(sortNotes);
      }
    };
    
    fetchNotes(params.createdNotes);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search