1

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
    )
}
5
  • 1
    I suggest using the built-in URLSearchParams API so you don't have to fiddle with (and probably mess up) creating query strings yourself. Commented Mar 24, 2023 at 15:14
  • If you want an answer, you have to tell us what exactly params is. It looks like params.section starts with a ?; otherwise, you wouldn't be creating a querystring. Commented Mar 24, 2023 at 15:20
  • section, currentPage and createdNotes are states, i gave the example of the array createdNotes because thats where i am having trouble i don't know how tu use map() to get multiple &notes[]=x in my url Commented Mar 24, 2023 at 15:23
  • Does this answer your question? javascript modify url parameter array Commented Mar 24, 2023 at 15:55
  • Does this answer your question? Adding parameters to URL, putting array in query string Commented Mar 24, 2023 at 16:07

1 Answer 1

0

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
  );
};
Sign up to request clarification or add additional context in comments.

6 Comments

This answer would be better suited on the duplicate
params.toString() returns %5B%5D instead of [] and %26 instead of &
@Elichy %5B%5D is explainable because that's the URI encoding of [], but why are you using &?
@HereticMonkey I don't think the target question is suitable. I think a better one would be stackoverflow.com/questions/39664019/…
@Elichy You don't need &. URLSearchParams will handle creating the final query string for you. Are you even using URLSearchParams (like my answer uses)?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.