-1

I want to add dynamic id to axios call method patch

axios. patch('classrooms/dynamic id here? Api _ key=9345c'. I tried ${id} but it gives an error id not defined

function postData(){

  axios.patch(`classrooms/${id}?api_key=${API_KEY}`,`subject=${change}`).then((res)=>
      console.log(res.data)
      
  ).catch((err)=> console.log(err));

}

I want to use this function onClick event so if I tried to define id using const postData() wont work . Any way to add Id dynamically?

Try
  • 1
  • 2
  • 1
    need to use backticks for string interpolation: `axios.patch(\`classrooms/${id}?Api _ key=9345c\`)`. – Nick Jul 03 '21 at 21:30
  • Does this answer your question? [How can I do string interpolation in JavaScript?](https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascript) – Nick Jul 03 '21 at 21:33
  • yes I used backtick still getting an error id is not defined – Try Jul 03 '21 at 21:59
  • Are you calling this from a web browser? can you use the developer console to see what your network request looks like? – Nick Jul 03 '21 at 22:00
  • function postData(){ axios.patch(`classrooms/${id}?api_key=${API_KEY}`,`subject=${change}`).then((res)=> console.log(res.data) ).catch((err)=> console.log(err)); } I want to pass this function onClick to update an api. – Try Jul 03 '21 at 22:08
  • if i add a specific id it works but i need it to be dynamic – Try Jul 03 '21 at 22:10
  • So it sounds like your `id` variable might be undefined. We need a lot more context (i.e., where and how `id` is defined` and where this request is executed to help – Nick Jul 03 '21 at 22:11
  • actually its an api system to allocate subjects to classrooms and students to classes. so what i want to do is , i need to assign a subject to a classroom, above mentioned is the link of classroom where i want to update. – Try Jul 03 '21 at 22:19

1 Answers1

0

did you try backticks ?

axios.patch(`classrooms/${id}?Api_key=9345c`)

this should work

Nick
  • 16,066
  • 3
  • 16
  • 32